mimo
mimo

Reputation: 6817

How to pass multiple values via operator chain to map operator? In NgRx Effect

I am working on Effect, in which I load new data form REST endpoint and then dispatch action to update store with received data. Together with composing searchUrl, there is some computation of newCurrentPage.

How to pass newCurrentPage value along with search request to following operatos?

Code looks like this:

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

This RxJS thing is quite new for me, and I haven't quite wrapped my head around it yet, so please be explicit. Thanks!

Upvotes: 0

Views: 1253

Answers (1)

Oles Savluk
Oles Savluk

Reputation: 4345

You can move operators to the closure where this variables were defined, like this:

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

Or use map operator to return pair of [response, newCurrentPage] so it can be used later

Upvotes: 1

Related Questions