ngrx效果多次调用http

时间:2017-12-08 07:54:25

标签: angular rest ionic-framework redux ngrx

我使用的是最新版本的ngrx(4.1.1)和棱角4.4.4,在这里找不到问题,可能需要一些帮助。

我正在使用一个调用this.apiProvider.getLogisticsFolder()的效果并使用http响应。一旦我的reducer返回新状态并且一切都按预期工作,我的休息服务被第二次甚至几次调用(动作/效果只被触发一次,其余的调用getLogisticsFolder())。

我在这里缺少什么?

@Effect()
syncFolders$ = this.actions$
    .ofType<LogisticsFolderActions.SyncFolders>(LogisticsFolderActions.SYNC_FOLDERS)
    .mergeMap(() => this.apiProvider.getLogisticsFolder()
        .withLatestFrom(this._store.select(state => state.logisticsFolders), this._store.select(state => state.settings))
        .map(([cloudLogisticsFolder, localLogisticsFolderState, settingsState]) =>
        {
            let tempLocalLogisticsFolder = localLogisticsFolderState.find(localLogisticsFolderState => localLogisticsFolderState.tenant === settingsState.baseURL);
            if (tempLocalLogisticsFolder)
            {
                //now check if the folder structure has been added, deleted or changed
                let updatedFolders = this.logisticsFolderProvider.checkAndProceedLogisticsFolderUpdate(cloudLogisticsFolder, tempLocalLogisticsFolder.logisticsFolders)
                this.logisticsFolderProvider.checkAndProceedTasksUpdate(cloudLogisticsFolder, updatedFolders)

                return new LogisticsFolderActions.SyncSuccess;
            } else
            {
                let logisticsFolderState = <LogisticsFolder.State>{};
                logisticsFolderState.tenant = settingsState.baseURL;
                logisticsFolderState.logisticsFolders = cloudLogisticsFolder;
                return new LogisticsFolderActions.SyncSuccess({ logisticsFolder: logisticsFolderState });
            }
        })
        .catch((error) =>
        {
            this._store.dispatch(new AppActions.UnexpectedError(error.json().message));
            return Observable.of(new LogisticsFolderActions.SyncFailed)
        })
    );

感谢您的帮助:)

1 个答案:

答案 0 :(得分:2)

...固定

我订阅了分配给this.token $的令牌,并且当状态更新时,执行了一个新值,因此我们有多个请求。

private oAuthRequest(options): Observable<any>
    {
        return this.token$.flatMap(token =>
        {
            options.headers = new Headers();
            options.headers.append('Content-Type', 'application/json');
            options.headers.append('Authorization', token);

            if (options.body && typeof options.body !== 'string')
            {
                options.body = JSON.stringify(options.body);
            }

            return this.http
                .request(new Request(options))
                .map((res: Response) =>
                {
                    if (res.text)
                    {
                        return res.json();
                    }
                    return res
                });
        }).take(1);

    }