如何通过运算符链将多个值传递给map运算符?在NgRx效应中

时间:2019-09-29 08:24:12

标签: javascript rxjs ngrx-store ngrx-effects

我正在Effect上工作,在其中我从REST端点加载新数据,然后调度动作以使用接收到的数据更新存储。与组成searchUrl一起,对newCurrentPage进行了一些计算。

如何将newCurrentPage值和搜索请求一起传递给以下操作符?

代码如下:

@Effect()
tablePageChanged = this.actions$
    .pipe(
        ofType(action.tablePageChanged ),
        withLatestFrom(this.store.select('tableData')),
        switchMap(([action, tableData]) => {

            let newCurrentPage: number;
            let searchUrl: string;

            switch (action.navPage) {

                case NavigationPage.First:
                    newCurrentPage = 1;
                    searchUrl = tableData.devsTable.firstUrl;
                    break;

                case NavigationPage.Previous:
                    newCurrentPage = tableData.devsTable.currentPage - 1;
                    searchUrl = tableData.devsTable.previousUrl;
                    break;

                case NavigationPage.Next:
                    newCurrentPage = tableData.devsTable.currentPage + 1;
                    searchUrl = tableData.devsTable.nextUrl;
                    break;

                case NavigationPage.Last:
                    newCurrentPage = Math.ceil(tableData.devsTable.totalRecords / tableData.devsTable.pageSize);
                    searchUrl = tableData.devsTable.lastUrl;
                    break;

                default:
                    break;
            }

            // HERE: I want to return also 'newCurrentPage', so that I can pass it to 'handleSuccessfulResponse' later
            return this.http.get<UserSearchResponse>(searchUrl, {observe: 'response'});
        }),
        withLatestFrom(this.store.select('tableData')),
        map(([response, tableData]) => {

            // HERE: I want to get 'newCurrentPage' to pass it to the 'handleSuccessfulResponse' function
            return this.handleSuccessfulResponse(response, tableData);
        })
    );

对我来说,RxJS这件事是很新的,我还没有完全解决这个问题,所以请明确。谢谢!

1 个答案:

答案 0 :(得分:1)

您可以将运算符移动到定义此变量的闭包处,如下所示:

switchMap(([action, tableData]) => {
  // ...
  return this.http.get<UserSearchResponse>(searchUrl, {observe: 'response'}).pipe(
    // `tableData` and `newCurrentPage` is available here
    map(response => this.handleSuccessfulResponse(response, tableData))
  );
})

或使用map运算符返回一对[response, newCurrentPage],以便以后可以使用

相关问题