【发布时间】:2019-09-29 11:34:34
【问题描述】:
尽管已在服务器端成功执行,但我的所有 Angular 发布请求都返回可观察到的错误。我不知道我做错了什么。
组件:
this.postInit.postInitialSetup(this.userForm).subscribe(
(data: string) => {
if (data === 'Posted Successfully') {
this.userForm.reset();
this.router.navigate([this.path]);
}
},
(error: any) => {
this.errored = true;
this.serviceErrors = error;
}
);
发出 HTTP 请求的服务:
import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpClient, HttpHeaders } from
'@angular/common/http';
import { map, catchError } from 'rxjs/operators';
import { FormGroup } from '@angular/forms';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SetupService {
initialSetUpUrl = 'api/initialSetup';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
constructor(private http: HttpClient) { }
postInitialSetup(postData: FormGroup) {
return this.http.post(this.initialSetUpUrl, postData.value,
this.httpOptions).pipe(
map((data: string) => {
return data;
}),
catchError(this.handleError)
);
}
private handleError(errorResponse: HttpErrorResponse) {
if (errorResponse.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', errorResponse.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${errorResponse.status}, ` +
`body was: ${errorResponse.error}`);
}
// return an observable with a user-facing error message
return throwError('Something bad happened; please try again later.');
}
}
考虑到对于 angular 和整个 observables 来说相对较新,有人可以帮我确定我在服务代码或组件代码中可能做错了什么。
【问题讨论】: