【发布时间】:2020-10-07 22:56:47
【问题描述】:
我是 Angular/Typescript 的新手,并且正在使用 catchError RxJs。我也在使用 .subscribe 和管道运算符。我想尽可能多地使用 observable,将它与 RxJS 操作符结合起来。在提交我的表单时,前端调用 API 并创建了一个新产品,并希望使用 HttpErrorResponse 对 400 和 500 的错误代码进行适当的错误处理。 我写了下面的代码,但不确定我是否正确地进行了错误处理,因为我得到了下面的错误(见底部)。
app.component.ts
onSubmit(): void {
if (this.form.valid) {
console.log('Creating product:', this.form.value);
this.http.post('/api/create', {
productName: this.form.value.productName,
}).pipe(catchError(err => {
if(err instanceof HttpErrorResponse && err.status == 500 || err.status == 502 || err.status == 503) {
this.err = "Server Side Error";
return throwError(err);;
}
else if(err instanceof HttpErrorResponse && err.status == 400){
this.err = "Bad Request";
return throwError(err);;
} else if(err instanceof HttpErrorResponse && err.status == 422){
this.err = "Unprocessable Entity - Invalid Parameters";
return throwError(err);;
}
})
.subscribe(
resp => this.onSubmitSuccess(resp), err => this.onSubmitFailure(err)
);
}
this.formSubmitAttempt = true;
}
private onSubmitSuccess(resp) {
console.log('HTTP response', resp);
this.productID = resp.projectID;
this.submitSuccess = true;
this.submitFailed = false;
}
private onSubmitFailure(err) {
console.log('HTTP Error', err);
this.submitFailed = true;
this.submitSuccess = false;
}
错误:
app.component.ts - 错误 TS2339:“AppComponent”类型上不存在属性“err”。
app.component.ts:124:16 - 错误 TS2339:“OperatorFunction”类型上不存在属性“subscribe”。}).subscribe(
【问题讨论】:
标签: angular typescript error-handling rxjs observable