Dan*_*l B 26 rxjs ngrx-effects angular ngrx-store angular5
我们刚刚将其中一个应用程序升级到Angular 5,并开始转换为rxjs v5.5中引入的lettable 运算符.
因此,我们使用.pipe()运算符将可观察的管道重写为新语法.
我们之前的代码看起来像这样,如果抛出错误,则.catch()内部.switchMap()不会中断效果的运行.
@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();
});
);
Run Code Online (Sandbox Code Playgroud)
如果在调用中抛出错误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);
}
})
);
Run Code Online (Sandbox Code Playgroud)
我怎样才能以类似的方式使用新语法捕获可观察管道中的任何抛出错误?
art*_*iak 39
重构后,您移出map了switchMap投影,因此任何错误都会关闭外部流.要保持两个流等效,您需要pipe在投影本身中使用:
import { empty } from 'rxjs;
// ...
@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)
.pipe(
map(result => {
if (!result) {
return new LoadDataFailed('Could not fetch data!');
} else {
return new LoadDataSuccessful(result);
}
}),
catchError((err, caught) => {
return empty();
})
)
)
);
Run Code Online (Sandbox Code Playgroud)