【问题标题】:Angular : prevent api error to not display HTML templateAngular:防止 api 错误不显示 HTML 模板
【发布时间】:2020-03-13 11:23:37
【问题描述】:

当我执行 HTTP 请求(例如 GET 请求)并且我得到无效给定数据的状态代码 400 时,它会阻止我的 HTML 模板显示在我的 Angular 应用程序的视图中。 这就是我目前的处理方式:

this.myService.getData(neededData)
  .subscribe(
    (result) => {
      this.data = result;
    },
    (error) => { 
      if (error) { 
        console.log("error"); 
        this.anErrorHasOccured = true; 
      }
    }
  );

“错误”在控制台中显示得很好,但是这个错误使我的模板无法显示,我该如何解决?

【问题讨论】:

    标签: angular api templates handle


    【解决方案1】:

    你可以试试这个吗:

    this.myService.getData(neededData)
      .pipe(catchError(err => {
        console.err(err);
        return of([]);
      }))
      .subscribe(
        (result) => this.data = result,
      );
    

    【讨论】:

    • 感谢帮助我,这是我从 VScode 得到的错误代码:Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable<Object>) => ObservableInput<any>'. Type 'void' is not assignable to type 'ObservableInput<any>'.
    • import { catchError } from 'rxjs/operators';
    • 你从 'rxjs/operators' 导入了正确的 { catchError }; ?
    • 是啊太棒了! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2017-01-26
    • 2021-01-27
    • 2018-07-28
    相关资源
    最近更新 更多