【发布时间】:2018-04-28 21:08:53
【问题描述】:
我们刚刚将我们的一个应用程序升级到 Angular 5,并开始转换为 rxjs v5.5 中引入的lettable operators。
因此,我们使用 .pipe() 运算符将可观察管道重写为新语法。
我们之前的代码看起来像这样,在.switchMap() 内部有一个.catch(),以便在抛出错误时不会中断效果的运行。
@Effect()
loadData$ = this.actions$
.ofType(LOAD_DATA)
.map((action: LoadData) => action.payload)
.withLatestFrom(this.store.select(getCultureCode))
.switchMap(([payload, cultureCode]) => this.dataService.loadData(payload, cultureCode)
.map(result => {
if (!result) {
return new LoadDataFailed('Could not fetch data!');
} else {
return new LoadDataSuccessful(result);
}
})
.catch((err, caught) => {
return Observable.empty();
});
);
如果在调用dataService 时出现错误,它将被捕获并处理(此处简化了错误处理)。
有了.pipe() 的新语法和使用,我们现在有了这个
@Effect()
loadData$ = this.actions$
.ofType(LOAD_DATA)
.pipe(
map((action: LoadData) => action.payload),
withLatestFrom(this.store.select(getCultureCode)),
switchMap(([payload, cultureCode]) => this.dataService.loadData(payload, cultureCode)),
map(result => {
if (!result) {
return new LoadDataFailed('Could not fetch data!');
} else {
return new LoadDataSuccessful(result);
}
})
);
如何使用新语法以类似的方式捕获可观察管道中抛出的任何错误?
【问题讨论】:
-
重构后,您将
map移出switchMap投影,因此任何错误都会关闭外部流。类似:switchMap(([payload, cultureCode]) => this.dataService.loadData(payload, cultureCode).pipe(map..., catch...))应该可以完成这项工作。 -
效果很好@arturgrzesiak!将其发布为答案,我会接受! :)
标签: angular rxjs ngrx-store ngrx-effects angular5