使用HttpClient核心角服务发送http请求的服务如下:
return this.httpService.get<MyObj[]>(myURL).pipe(catchError(errorHandle));errorHandle:作为属性传递给调用.get()的函数
我从我的nodejs服务器发送了一个400坏的请求,这个请求由以下errorHandle接收:
handleError(error: HttpErrorResponse) {
this.isLoading = false;
if(error.error instanceof ErrorEvent) {
this.error = error.error.message;
} else {
this.error = "Backend server error, status code:" + error.status
}
return throwError('Something bad happened');
}现在,在UI中使用this.isLoading来防止div呈现,而是显示“加载.”。当我在handleError中将其设置为false时,它确实会更新属性,但它不会影响UI。它一直在装货..。
供参考的代码:
组件:
handleError(error: HttpErrorResponse) {
this.isLoading = false;
if(error.error instanceof ErrorEvent) {
this.error = error.error.message;
} else {
this.error = "Backend server error, status code:" + error.status
}
return throwError('Something bad happened');
}
ngOnInit() {
//returns 400 Bad Request
this.variablesService.getVariables(URL.MODELVARIABLE+','+URL.METRICVARIABLE, this.handleError).subscribe(variables => {
this.fetchedVariables = variables.map(variable => new Variable(variable));
this.variables = this.fetchedVariables.filter(variable => variable.isglobal);
this.populateGridItems(GRIDNAME.GlobalVariable, this.variables);
this.isLoading = false;
});
}UI:
<error [error]="error"></error> <!-- content which should show as ive set this.error but still doesnt -->
<div *ngIf="!isLoading && !error">
...content that doesnt show which is fine
</div>
<p *ngIf="isLoading">Loading..</p> <!-- keeps showing even when ive set it to false -->发布于 2018-08-10 16:27:44
您“处理”错误,然后重新抛出它,并且永远不会处理重新抛出的错误,而未处理的错误会破坏可观察到的流。你有两个选择:
不要重新抛出错误
handleError(error: HttpErrorResponse) {
this.isLoading = false;
if(error.error instanceof ErrorEvent) {
this.error = error.error.message;
} else {
this.error = "Backend server error, status code:" + error.status
}
return empty();
}或处理要订阅的第二个参数中重新引发的错误:
this.variablesService.getVariables(URL.MODELVARIABLE+','+URL.METRICVARIABLE, this.handleError).subscribe(variables => {
this.fetchedVariables = variables.map(variable => new Variable(variable));
this.variables = this.fetchedVariables.filter(variable => variable.isglobal);
this.populateGridItems(GRIDNAME.GlobalVariable, this.variables);
this.isLoading = false;
},
(error) => console.log(error, "do whatever you want here"));https://stackoverflow.com/questions/51790512
复制相似问题