Angular 6-发生错误后UI冻结

时间:2018-08-10 16:22:33

标签: javascript html angular http

服务使用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');
}

现在,this.isLoading用于UI来防止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;
    });
}

用户界面:

<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 -->

1 个答案:

答案 0 :(得分:4)

您“处理”了错误,但随后又将其抛出并从不处理重新抛出的错误,未处理的错误中断了可观察到的流。您有2个选择:

不要抛出错误

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"));