ngrx/effects - 依赖于其他动作的动作

ngrx/effects - Actions that are depedent on other actions

从 API 获取数据时,我首先需要检查我是否已经存储了令牌,以及它是否仍然有效。如果没有,我需要从 API 获取一个新的并等待 GET_TOKEN_SUCCESS 操作,然后才能发出实际的数据请求。

如何使用 ngrx/effects 处理这种情况,而不必在一个效果中编写所有逻辑?

一种解决方案是发出获取令牌的操作,然后在收到令牌时重新发出效果的操作。你可以这样做:

@Injectable()
export class UserEffects {

    private _tokens: Observable<TokenState>;

    // Inject the store so that the token can be selected and validated in any
    // effects.

    constructor(private _actions_ Actions, private _appStore: Store<AppState>) {
        this._tokens = this.appStore_.select<TokenState>("token");
    }

    @Effect()
    createUser = this._actions
        .ofType("CREATE_USER_REQUEST")

        // Combine the action with the latest token from the app state.

        .withLatestFrom(this._tokens, (action, token) => [action, token])
        .switchMap(([action, token]) => {

            if (isValidToken(token)) {

                // If the token is valid, perform the effect. For example,
                // this uses a promise-based service:

                return Observable
                    .fromPromise(this._userService.createUser(token, action.payload))
                    .map((user) => ({
                        type: "CREATE_USER_SUCCESS",
                        payload: user
                    })
                    .catch((error) => Observable.of({
                        type: "CREATE_USER_ERROR",
                        payload: error
                    }));

            } else {

                // If the token is invalid, emit a series of observables.
                // The first emits the action to get the token and the
                // second re-emits the original action after the token has
                // been successfully received.

                return Observable.concat(
                    Observable.of({ type: "GET_TOKEN_REQUEST" }),
                    this._actions.ofType("GET_TOKEN_SUCCESS").first().map(() => action)
                );
            }
        });
}

您可以使用一个函数(它传递了动作、令牌和效果行为的可观察对象——即上面示例中带有服务调用的可观察对象)来执行标记验证和可观察对象串联,因为里面没有特定效果的东西。