在服务器发出错误响应后,我的应用程序不会再发送任何请求。
我发送请求时:
getMachineRules(rules: Array<string>): Observable<RulesResults> {
return this.http.post<RulesResults>('/rules', { nodes: rules })
.pipe(
catchError(this.handleError)
);
}我的errorHandler:
handleError(error) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${JSON.stringify(error.error)}`);
}
return throwError('Something bad happened; please try again later.');
}我的管道是这样的:
ngAfterViewInit() {
this.rulesChanged
.pipe(
startWith({}),
switchMap(() => {
this.isLoadingResults = true;
return this.settings.getMachineRules(this.currentRules);
}),
map(data => {
this.isLoadingResults = false;
this.resultsLength = data.inputs?.length || 0;
return data;
}),
catchError(e => {
console.log("Error caught");
this.isLoadingResults = false;
this.resultsLength = 0;
return observableOf({ inputs: [] } as RulesResults);
})
).subscribe(
data => { return this.updateRules(data); },
);
}我可以在控制台中看到“捕获的错误”消息,即使在错误情况下,updateRules()方法似乎也能正常工作。
但是,在404-Error响应之后,不再调用ngAfterViewInit()方法。UI钢对交互作用作出反应。
发布于 2020-12-14 17:23:17
一旦Obsevable失败,您就无法再次激活它,catchError用于通过返回新的可观察或抛出错误来处理错误。如果主流失败,observableOf({ inputs: [] } as RulesResults)将作为替代,这意味着您的主要可观察到的永远不会再次发出。
考虑在管道的末尾使用retry,或者让您的catchError返回可观察到的源本身,如下所示:
catchError((error, source) => {
....
return source;
})或者将catchError操作符放置在switchMap中,以便只有内部流会失败,而外部(主)流将保持活动状态,如下所示:
ngAfterViewInit() {
this.rulesChanged
.pipe(
startWith({}),
switchMap(() => {
this.isLoadingResults = true;
return this.settings.getMachineRules(this.currentRules).pipe(
map(data => {
this.isLoadingResults = false;
this.resultsLength = data.inputs?.length || 0;
return data;
}),
catchError(e => {
console.log("Error caught");
this.isLoadingResults = false;
this.resultsLength = 0;
return observableOf({ inputs: [] } as RulesResults);
})
)
})
).subscribe(
data => { return this.updateRules(data); },
);https://stackoverflow.com/questions/65293193
复制相似问题