【问题标题】:Catching error in Angular 9 with catchError operator使用 catchError 运算符在 Angular 9 中捕获错误
【发布时间】:2020-10-31 14:45:40
【问题描述】:

您好,我尝试使用 Rxjs 运算符 catchError 捕获错误并发送有关日志的信息。下面我展示了我的帖子服务中用于获取一些数据的函数:

fetchPosts() {
    const  url = 'some url';
    return this.http.get<{ [key: string]: Post }>(url)
      .pipe(
        map((responseData) => {
            const postArray: Post[] = [];
            for (const key in responseData) {
              if (responseData.hasOwnProperty(key)) {
                postArray.push({...responseData[key], id: key});
              }
            }
            return postArray;
          }, catchError(errorResponse => {
              // now we can send for example information to analytic serv
          this.logService.addNewLog(errorResponse.message);
          return throwError(errorResponse.message);
          })
        ));
  }

问题是它不适用于地图运算符。当我删除地图运算符时,它将正常工作。如下:

fetchPosts() {
    const  url = 'some url';
    return this.http.get<{ [key: string]: Post }>(url)
      .pipe(catchError(errorResponse => {
          this.logService.addNewLog(errorResponse.message);
          return throwError(errorResponse.message);
          })
        );
  }

我该如何解决这个问题?我希望它可以与这两个运算符一起使用:map、catchError。我的代码有什么问题?我很乐意提供帮助。

【问题讨论】:

    标签: angular typescript error-handling rxjs


    【解决方案1】:

    操作员必须单独通过管道输入。目前,您正在map 运算符内的catchError 中进行管道传输。试试下面的

    fetchPosts() {
      const  url = 'some url';
      return this.http.get<{ [key: string]: Post }>(
        'https://http-request-learning.firebaseio.com/posts.json'
      ).pipe(
        map((responseData) => {
          const postArray: Post[] = [];
          for (const key in responseData) {
            if (responseData.hasOwnProperty(key)) {
              postArray.push({...responseData[key], id: key});
            }
          }
          return postArray;
        }),              // <-- close `map` here
        catchError(errorResponse => {
          // now we can send for example information to analytic serv
          this.logService.addNewLog("sss");
          return throwError(errorResponse.message);
        })
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-07
      • 1970-01-01
      • 2019-07-31
      • 2020-09-29
      • 2020-12-12
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      相关资源
      最近更新 更多