首页 > 解决方案 > 如何从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:当服务器响应时,我的商店工作得很好,但是当它没有响应时,我的错误不会被发送到可观察的商店状态的订阅。

标签: angularngrx

解决方案


我认为您在这里遇到的问题是,您似乎正试图将错误作为可观察链中的错误推送到您的商店,而不是使错误成为您状态的另一部分。

您正在寻找的更像是:

// 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字段的值将让您知道请求是否失败以及是否已调度任何错误(我建议为此创建一个选择器,您可以直接订阅)。

我自己也没有尝试过,但我有一种感觉,尝试以这种方式对可观察的存储进行错误操作会杀死应用程序中的存储,因此不应该真正尝试。


推荐阅读