首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >使用catchError操作符捕获Angular 9中的错误

使用catchError操作符捕获Angular 9中的错误
EN

Stack Overflow用户
提问于 2020-10-31 14:45:40
回答 1查看 23关注 0票数 0

您好,我尝试使用Rxjs operator catchError捕获错误并发送有关日志的信息。下面我展示了在我的post服务中使用的函数,负责获取一些数据:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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);
          })
        ));
  }

问题是它不能和map运算符一起工作。当我删除地图操作符时,它将正常工作。如下所示:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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。我的代码出了什么问题?如果能帮上忙,我会很感激的。

EN

回答 1

Stack Overflow用户

发布于 2020-10-31 14:48:35

运算符必须通过管道单独输入。此时,您正在通过管道在map操作符中输入catchError。请尝试以下操作

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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);
    })
  );
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64622932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文