【发布时间】:2021-02-03 22:05:30
【问题描述】:
由于某种原因,我的 Angular 代码无法正确处理 POST 请求的错误条件。
对于上下文,相关调用在 component.ts 中:
this.crazyService.addSomething(stringifiedContent).subscribe(
data => {
console.log(data);
this.showSuccess();
setTimeout(() => {
this.dashboardRedirect();
}, 2750);
}
)
在'crazyService'中的代码是
addSomething(something: any): Observable<any> {
const headers = { 'content-type': 'application/json' };
const body = JSON.stringify(something);
return this.http
.post<any>(this.relevantUri, body, { headers, observe: 'response' })
.pipe(
catchError(err => {
console.error(err);
throw err;
})
);
}
POST 请求工作正常,但由于某种原因,console.log(data)、this.showSuccess() 和 timeOut 在这里不起作用。
而当我在我的组件中执行此操作时:
this.crazyService.addSomething(stringifiedContent).subscribe( hello => {
console.log(hello);}
, data => {
console.log(data);
this.showSuccess();
setTimeout(() => {
this.dashboardRedirect();
}, 2750);
}
)
它进入数据部分并做我想做的事情,而在前面的例子中它似乎没有进入那个块。
为什么会这样?我该如何解决这个问题,以便我可以有一个 POST 请求成功的案例,以及另一个错误的案例?
【问题讨论】:
标签: angular post service rxjs observable