angular - 如何从ngrx商店中的选择中获取错误?
问题描述
假设我的商店可以使用一些操作:Load、LoadFail 和 LoadSuccess。我所有的动作都非常简单,LOAD = "load"
, LOAD_FAIL = "load failed"
,并且LOAD_SUCCESS = "load success"
我有一个简单的减速器可以打开这些,如下所示:
export function reducer(state: State = initialState, action: Actions): State {
switch (action.type) {
case Actions.LOAD: {
console.log("Actions.LOAD");
return state;
}
case Actions.LOAD_FAIL: {
console.log("Actions.LOAD_FAIL");
store.error = action.payload;
return state;
}
case Actions.LOAD_SUCCESS: {
console.log("Actions.LOAD_SUCCESS");
state.data = action.payload;
return state;
}
default: {
return state;
}
}
}
我有一个处理负载调度的效果类:
@Injectable()
export class TestersEffects {
constructor(
private service: MyHttpService,
private actions$: Actions
) {}
@Effect() load$ = this.actions$.pipe(
ofType(Actions.LOAD),
switchMap(
action => {
return this.service.load().pipe(
map(data => {
console.log("load$ fired");
return new TestersActions.LoadSuccess(data);
}),
catchError(error => {
console.log("error");
return of (new Actions.LoadFail(error));
})
)
}
)
);
}
最后,我正在使用所有这些:
export class MyClass implements OnInit {
data: any;
constructor(private store: Store<AppState>) {}
ngOnInit() {
this.store.dispatch(new Actions.Load());
this.store.select(store => store.State).subscribe(
data => this.data = data,
error => this.handleError(error)
);
}
handleError(error) {
//Whatever I'll do to handle this error
}
}
当我请求的服务器响应时,此代码工作正常。但是,我需要处理它没有响应的情况。我假设我根本不了解ngrx/store 的流程,无法完全理解如何得到我的错误,但我不知所措。当我调试我的代码时,catchError
我的效果类中的触发并发送一个 LoadFail 操作,reducer 捕获该操作,设置错误并返回状态。但是,在我的订阅方面MyClass
,我什么也没看到。我想我一定在这里遗漏了一些关键的东西,但我所有的谷歌搜索专业知识都让我两手空空,我想我会勇敢地 Stack Overflow 并乞求它在这件事上的智慧。
tl; dr:当服务器响应时,我的商店工作得很好,但是当它没有响应时,我的错误不会被发送到可观察的商店状态的订阅。
解决方案
我认为您在这里遇到的问题是,您似乎正试图将错误作为可观察链中的错误推送到您的商店,而不是使错误成为您状态的另一部分。
您正在寻找的更像是:
// Add a property to your state object to hold errors...
interface State {
// ...
error: Error | null;
}
// Then in your reducer...
case Actions.LOAD_FAIL: {
console.log("Actions.LOAD_FAIL");
return { ...state, error: action.error };
}
然后在您的订阅中询问商店中此error
字段的值将让您知道请求是否失败以及是否已调度任何错误(我建议为此创建一个选择器,您可以直接订阅)。
我自己也没有尝试过,但我有一种感觉,尝试以这种方式对可观察的存储进行错误操作会杀死应用程序中的存储,因此不应该真正尝试。
推荐阅读
- php - PHP Slim 3 API 中间件类不能来自 __invoke 的方法?
- mysql - 相同记录集上的相同 UPDATE SQL 似乎与 MariaDB 行为不端
- node.js - google sheet api v4 在特定行之后附加行或将行移动到特定位置
- python - 如何将注释箭头添加到图例
- haskell - 我可以用“递归方案”“cata”来写“foldr”(或“foldMap”)吗?
- sql - SQL Server 比较 varbinary 列
- reactjs - 如何将地图函数用于钩子 useState 属性
- python - Python configparser:获取未使用条目的列表
- html - 如何摆脱表格中的“红色区域”?
- mysql - 是否有 mysql 函数可以从 SCHEMA(date, time) 形式的可用数据中获取过去三天时间的平均值