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

时间:2016-11-08 16:17:43

标签: angular ngrx

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

如何使用ngrx/effects处理此方案而无需在一个效果中编写所有逻辑?

1 个答案:

答案 0 :(得分:0)

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

@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)
                );
            }
        });
}

你可以使用一个函数来干这个(它传递了动作,令牌和效果行为的observable - 即上面例子中带有服务调用的observable)来执行令牌验证和可观察的连接,因为它是那里没有任何特定效果。