我如何处理捕获错误在多个地方在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;
}
);

你做得对。

两个方法的错误最终会出现在(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);
}
);

的回报:"糟糕,

最新更新