我目前正在用Sping Boot 做一个Angular项目。我是Web编程的新手,所以我还有一些障碍要克服。我想做的是,向后端发送PUT请求以更改现有对象的名称(在这个例子中,它是一个类别的名称)。但我总是得到一个415错误,当我想发送请求。我不知道如何以及在哪里正确设置媒体类型。有人能帮我吗?
import { Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core';
import { Category } from "../../types/category";
import { ActivatedRoute, Router } from "@angular/router";
import { AbstractControl, FormControl, FormGroup, Validators } from "@angular/forms";
import { Subject } from "rxjs";
import { CategoryService } from "../../services/category.service";
import { CategoryCustomValidatorService } from "../../validators/category-custom-validator.service";
import { takeUntil } from "rxjs/operators";
import { HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-edit-category',
templateUrl: './edit-category.component.html',
styleUrls: ['./edit-category.component.scss']
})
export class EditCategoryComponent implements OnInit, OnDestroy {
public createForm?: FormGroup;
public category: Category = {id: '', name: '', description: ''};
public onDestroy$ = new Subject<void>();
public headers = new HttpHeaders({'Content-Type': 'application-json'});
@Output()
public categoryCreateEvent: EventEmitter<Category> = new EventEmitter<Category>();
public constructor(
private route: ActivatedRoute,
private router: Router,
private categoryService: CategoryService,
private customValidatorService: CategoryCustomValidatorService
) {
}
public ngOnInit(): void {
this.initCreateForm();
}
public ngOnDestroy(): void {
this.onDestroy$.next();
}
public onSubmit(): void {
if (this.createForm && this.createForm.valid) {
const {name, description} = this.createForm.getRawValue();
this.category.name = name;
this.category.description = description;
this.categoryService.findById(this.category.id);
this.categoryService
.update(this.category, this.category.id, this.headers)
.pipe(
takeUntil(this.onDestroy$)
)
.subscribe((category: Category) => {
this.onCreateSuccess(category);
});
}
}
public initCreateForm(): void {
this.createForm = new FormGroup({
name: this.createNameControl(),
description: new FormControl('',
{nonNullable: true})
});
}
public isFormNotValid(): boolean {
if (!this.createForm) {
return true;
}
return this.createForm.invalid;
}
public isNameNotValid(nameControl: AbstractControl<string> | null): boolean {
if (nameControl === null) {
return true;
}
return nameControl.touched && nameControl.invalid;
}
public getValidationErrorMessage(nameControl: AbstractControl<string> | null): string {
if (nameControl === null) {
return '';
}
if (nameControl.errors === null) {
return "Name is acceptable.";
}
if (nameControl.errors['required']) {
return 'Name is required, please provide a name';
}
return 'Name is already used, please provide another name.';
}
private onCreateSuccess(category: Category): void {
this.categoryCreateEvent.emit(category);
this.createForm?.reset();
}
private createNameControl(): FormControl<string> {
return new FormControl(
'',
{
validators: [Validators.required, Validators.minLength(1)],
asyncValidators: [this.customValidatorService.asyncUnique()],
nonNullable: true
}
);
}
}
我已经尝试在组件类中将媒体类型设置为application/JSON,但没有成功,而且当我通过Postman发送请求时,一切都正常。
import { Injectable } from '@angular/core';
import { Observable } from "rxjs";
import { Category } from "../types/category";
import { HttpClientService } from "../../HttpParameters/services/http-client.service";
import { HttpHeaders } from '@angular/common/http';
@Injectable()
export class CategoryService {
private categoryUrl: string = "categories";
public constructor(private httpClientService: HttpClientService) {
}
public findAll(): Observable<Category[]> {
return this.httpClientService.get<Category[]>(this.categoryUrl);
}
public findById(id: string): Observable<Category> {
return this.httpClientService.get<Category>(this.categoryUrl);
}
public create(category: Category): Observable<Category> {
return this.httpClientService.post<Category>(this.categoryUrl, category);
}
public isNameUnique(name: string): Observable<boolean> {
const params = {
name: name.trim()
};
return this.httpClientService.get<boolean>(`${this.categoryUrl}/validation`, {params});
}
public update(category: Category, id: string, param?: HttpHeaders): Observable<Category> {
id = '59';
return this.httpClientService.put<Category>(`${this.categoryUrl}/${'59'}`);
}
}
这是我目前为止的分类服务。
import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { environment } from "../../../environments/environment";
import { Observable } from "rxjs";
import { HttpParameters } from "src/app/HttpParameters/types/HttpParameters";
@Injectable({
providedIn: 'root'
})
export class HttpClientService {
protected apiUrl = environment.apiPath;
public constructor(private http: HttpClient) {
}
public get<T>(path: string, param?: HttpParameters): Observable<T> {
return this.http.get<T>(`${this.apiUrl}/${path}`, param);
}
public post<T>(path: string, object: T): Observable<T> {
return this.http.post<T>(`${this.apiUrl}/${path}`, object);
}
public put<T>(path: string, param?: HttpParameters): Observable<T> {
return this.http.put<T>(`${this.apiUrl}/${path}`, path);
}
public delete<T>(path: string): Observable<T> {
return this.http.delete<T>(`${this.apiUrl}/${path}`);
}
}
这是HttpClientService。
1条答案
按热度按时间9lowa7mx1#
你在HttpClientService的put方法中传递了一个路径作为请求主体,你可能应该传递updated对象,类似于你的post方法。