首页 > 解决方案 > 如何处理 Angular 流中多个位置的捕获错误?

问题描述

现在,我正在尝试确保在首先获取组 id 的流中正确处理错误,然后使用该组 id 获取配置文件信息。

我需要它,所以很明显哪个步骤导致了错误——要么是获取 groupId,要么是获取配置文件信息。

现在我有这样的东西,但我不确定这是否正确。

this.groupRepository
    .getUserGroup()
    .pipe(mergeMap(group) => {
        return this.profileRepository.getAllProfiles(group.id)
    })
    .subscribe(
        (res) => {
            // doing things in here to set the groups and profiles
        },
        (error) => {
            this.error = error;
        }
    );

标签: javascriptangularerror-handlingrxjs

解决方案


你做对了。

两种方法的错误最终都会出现在(error) => {...}方法中。

小测试:

of('A', 'B', 'C').pipe(mergeMap(letter => {
  return of('E', 'F', 'G');
})).subscribe(
    (res) => {
      console.log(res);
    },
    (error) => {
      console.log(error);
    }
  );

返回:'E'、'F'、'G'、'E'、'F'、'G'

使用第二种方法抛出:

of('A', 'B', 'C').pipe(mergeMap(letter => {
  return throwError('bad');
})).subscribe(
    (res) => {
      console.log(res);
    },
    (error) => {
      console.log(error);
    }
  );

返回:“坏”

使用第一种方法抛出:

throwError('bad').pipe(mergeMap(letter => {
  return of('E', 'F', 'G');
})).subscribe(
    (res) => {
      console.log(res);
    },
    (error) => {
      console.log(error);
    }
  );

返回:“坏”


推荐阅读