我想对 api 调用进行 3 个操作。GetItem、GetItemFailed、GetItemSuccess。
我对 rxjs 运算符不太熟悉,所以我只使用 subscribe 进行 api 调用。
像这样的东西:
@Action(GetItem)
getItem(sc: StateContext<ItemStateModel>, { payload }: GetItem) {
sc.patchState({
isLoading: true
});
this.itemService.getItem(payload)
.subscribe(item => {
sc.dispatch(new GetItemSuccess(item));
}, error => {
sc.dispatch(new GetItemFailed(error));
});
}
我做了一些谷歌搜索 ngxs 示例,发现大多数人使用带有 tap/take/first 的管道,因此我将操作中的 subscribe 重构为如下内容:
return this.itemService.getItem(payload).pipe(
tap(({ item }) => {
return sc.dispatch(new GetItemSuccess(item));
}),
catchError(({ error }) => {
return sc.dispatch(new GetItemFailed(error));
})
);
它起作用了,但是当我检查 redux 开发工具时,GetItemSucess 在 GetItem 之前首先被触发。
谁能告诉我在成功/失败的情况下调用 api 的正确方法。似乎无法在网上找到一个很好的例子。