Learn the best strategy for efficiently passing multiple values through an operator chain to the map operator in NgRx Effects!

In my current project, I am working on the "Effect" feature. This involves loading new data from a REST endpoint and then dispatching an action to update the store with the received data. In addition to composing the "searchUrl", there is also some computation involved in determining the value of "newCurrentPage".

I'm trying to figure out how to pass the value of "newCurrentPage" along with the search request when using the following operators:

The code snippet 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;
            }

            // At this point, I would like to return the 'newCurrentPage' as well, so that it can be passed to 'handleSuccessfulResponse' later
            return this.http.get<UserSearchResponse>(searchUrl, {observe: 'response'});
        }),
        withLatestFrom(this.store.select('tableData')),
        map(([response, tableData]) => {

            // Here, I need to access the 'newCurrentPage' value to pass it to the 'handleSuccessfulResponse' function
            return this.handleSuccessfulResponse(response, tableData);
        })
    );

I am still trying to fully grasp RxJS, so if you could provide clear explanations, it would be greatly appreciated. Thanks!

Answer №1

To improve efficiency, consider moving operators to the closure where the variables were defined, as shown below:

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

Alternatively, utilize the map operator to return a pair of [response, newCurrentPage] for later use.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Angular 1.x, utilizing both ES5 and ES6, and incorporating Karma for comprehensive testing

I am currently developing tests for an angular app that consists of a mix of ES5 and ES6 files. To transpile the ES6 files, I am using babel CLI with the options --modules system --module-ids. Here is an example of what I have: ES5 file: angular.module(& ...

Swapping out video files with varying quality using HTML5 and Jquery

Objective: Implementing a feature to change the video being played when a user clicks a button using Jquery. Example website for reference: (click on the "hd" button in the player control) More details: When the page loads, the browser will play the fi ...

I have to display a pop-up message box after selecting an option from a dropdown menu that fulfills a set of conditions

I am attempting to display a pop-up message when a selection is made on a dropdown menu that meets specific criteria. The dropdown list is generated from a coldfusion output query. I am relatively new to JavaScript, so I may be missing something in my code ...

Building a single page web application using TypeScript and webpack - a step-by-step guide

For a while now, I've been working on single page applications using Angular. However, I'm interested in creating a single page application without utilizing the entire framework. My goal is to have just one .html file and one javascript file, w ...

I would like to give the option for file uploads, but the form refuses to submit unless a file is uploaded

I've recently developed a form in React and React Bootstrap, and I've encountered an issue with the file upload feature. I want the file upload to be optional, but when I try to submit the form without uploading a file, it doesn't work as ex ...

attempting to eliminate on-screen buttons by hovering over the video

Is there a way to make my video play on loop like a GIF without the controls ever showing? I want it to have a seamless playback experience. Any ideas would be appreciated. P.s. Don't worry about any StackOverflow errors when running the snippet. Than ...

Customizing the default image of a Select dropdown field in Sencha Touch

Does anyone know how to change the default image of a select dropdown in Sencha Touch to a customized image? I've attached a screenshot for reference but can't seem to find any properties or classes to adjust this. Any guidance would be greatly a ...

How can I inject an isolated scope object into an Angular custom directive template?

Having trouble using an object in an angular template within a custom directive. Take a look at this plunker to see the issue I'm facing. After some experimentation, I realized that I need to utilize scope: {address: '='} to pass an object ...

Looking for a prerequisite for running this script?

Seeking assistance from a skilled Javascript expert. I specialize in template development and utilize a specific script to display my footer link in all the free templates I create. If someone attempts to remove the footer link, their site will be redirec ...

What is the secret to planning an event that spans a significant period of time?

Let's say there's this div in the code: <div [hidden]="!isNotificationDisplayed" class="notification"> <h2 align="center" class="set-margin" #notification>Node was...!</h2> <h4 alig ...

Learn how to effectively utilize templateURL in an express and angular project

Our project utilizes Express without any view engine. To set up static directories, we have the following: app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/view')); app.use(express.static(__dirname + ...

Guiding you on exporting a Typescript class with parameters in Node.js

Trying to find the Typescript equivalent of require('mytypescriptfile')(optionsObject); This is the TS code provided: export class Animal { name: string; public bark(): string { return "bark " + this.name; } constructor(color:string) ...

Barba.jS is causing a delay in loading scripts after the page transition

One of my index files includes Gsap and Barba JS, while an inner page includes additional JS files such as locomotive.js and OWLcarousel.js. These two JS files are not necessary for the index page. However, when transitioning from the index page to the inn ...

Retrieving user input from an angular controller function

I have a $resource object in Angular that looks like this: { _id: '1' items: [ {_id: 'a'}, {_id: 'b'}, {_id: 'c'} ] } My goal is to create a form with a checkbox for each element in the items array. In th ...

What is the proper way to store the output in a variable? Angular and XLSX

I am attempting to read an Excel file from an input using Angular and convert the data into an array of objects. Here is how my components are structured: import * as XLSX from 'xlsx'; import { Injectable } from '@angular/core'; @Injec ...

Manipulate HTML Table to Obtain Value of First Column Cell When Another Cell is Clicked using Javascript

I have a PHP web application where I am retrieving data from MySql and displaying it in the HTML table below. <table id = "table" width="500px" cellpadding=2 celspacing=5 border=2 > <tr> <th>Subject Code</th> <th>Subje ...

Trouble arises with AJAX due to DOM traversal errors

I am trying to set up a system for liking and disliking with a counter. However, I am facing issues with my AJAX call, specifically when attempting to change the HTML of selected elements in the view after sending values to the DB. The element in question ...

What is the best location for storing your front-end javascript files?

As I work on my web application using Express, I've utilized the application skeleton provided by the express-generator. To bundle my client-side assets, I've integrated webpack into my project. Now, I'm faced with a dilemma on where to st ...

Differences between Geo location in JavaScript and JSON

Currently, I am attempting to fetch the geolocation data of the user browsing by utilizing maxmind's free service at jQuery.getScript('http://j.maxmind.com/app/geoip.js', function() { var country = geoip_city(); console.log("Your ...

Attach an event to the HTML document's element and utilize addEventListener on the same element

What sets apart the logical/programming difference? I found myself responding to a duplicated question and decided to change one of the repetitive answers with a fresh perspective (in my opinion, even though it appears longer): for (i = 1; i <= 10; i++ ...