Use RXJS to prevent having multiple nested subscriptions

I am looking to revamp the code snippet below:

 this.dataUserSubscription = this.store$.pipe(select(selectUser)).subscribe(
            user => {
                this.store$.pipe(select(selectUserData, {user}), take(1))
                    .subscribe(userData => {
                        if (userData === null) {
                            this.store$.pipe(select(selectUserManagement, {user}), take(1)).subscribe(
                                userManagement => {
                                    this.store$.dispatch(saveUserDataToStore({
                                        user,
                                        userManagement
                                    }));
                                });
                        }
                    });

I am seeking a solution that eliminates nested subscriptions. Most examples I've come across involve just two subscriptions.

 this.dataUserSubscription = this.store$.pipe(select(selectUser),
    switchMap(user => this.store$.pipe(select(selectUserData, {user}))))
    .subscription(userData => {
        // logic
    })

The above solution does not fit my specific scenario. What is the right approach for removing multiple nested subscriptions in this case?

Answer №1

In accordance with RxJS best practices, the second example you provided is considered a suitable approach.

However, following NgRx best practices, it is recommended to eliminate the nested subscription by combining your selectors.

Without access to your specific selector files, it's difficult to provide an exact solution. If the user is already stored, you should be able to retrieve the user data without making two separate selector calls.

You could potentially implement something like:

const getDataForUser = createSelector(
    selectUser,
    selectUsers,
    (user, userDataDictionary) => userDataDictionary[user.id]
)

Then simply utilize the single getDataForUser selector for your data retrieval needs.

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

Using HttpClient to make a POST request to a json file on a local server

I have a `data.json` file located in the assets folder of my Angular application. The file path is as follows: MyApp => src => assets => data.json I am trying to make a `POST` request to this file using HttpClient in a component within the app ...

I'm attempting to retrieve an image from the database to display in the modal, but unfortunately the image isn't appearing as expected within the modal

I have the following code snippet for fetching an image: <img src="pics/file-upload-image-icon-115632290507ftgixivqp.png" id="image_preview1" class="img-thumbnail" style="margin-top: 15px; height:50%; width:20%"&g ...

Steps to Validate a Form: To allow the submit button to be enabled only when all input fields are filled out; if any field is left empty,

https://i.sstatic.net/AHlJX.png Is it possible to enable the send offer button only after both input boxes are filled? I'm sharing my code base with you for reference. Please review the code and make necessary modifications on stackblitz 1. exampl ...

When using videojs, I have the ability to include a Text Track event handler, however, there is currently no option to remove it

I implemented a listener for the 'cuechange' event on a Text Track and it's functioning correctly. However, I am unable to figure out how to remove this listener. I have attempted the instructions below to remove the listener, but it continu ...

An error has occurred in the tipo-struttura component file in an Angular application connected with a Spring backend and SQL database. The error message indicates that there is a TypeError where the

Working on my project that combines Spring, Angular, and MYSQL, I encountered a challenge of managing three interconnected lists. The third list depends on the second one, which in turn relies on user choices made from the first list. While attempting to l ...

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...

Is there a way to determine the expected gas fee for a specific contract function?

Currently, I am trying to retrieve an estimated gas consumption for a specific ERC20 method, particularly the "transfer" method. Based on the ethers.js documentation, the "BaseContractMethod" includes an "estimateGas" method that, when provided with an ar ...

Learn how to manipulate Lit-Element TypeScript property decorators by extracting values from index.html custom elements

I've been having some trouble trying to override a predefined property in lit-element. Using Typescript, I set the value of the property using a decorator in the custom element, but when I attempt to override it by setting a different attribute in the ...

Using Angular to assign a CSS variable to the before/after pseudo-classes

Having trouble passing a variable with [ngStyle] and reading it on the ::before class, any guidance in the right direction would be much appreciated! CSS: .handle-slider__control { height: 7px; z-index:1; background: $colour-alto; positi ...

Steps to automatically update a component when the button is clicked

Is there a way to change the displayed component in my parent component when clicking on a specific element? I currently have a pie chart component displaying by default but would like to switch it to another component with a different diagram when clickin ...

Accessing Nested FormGroup in Angular 6 by its name

Dealing with Nested Form Groups address = new FormGroup({ 'com.complex.Address':new FormGroup({ city: cityControl, streetName: streetNameControl, houseNumberAddition: houseNumberAdditionControl, ho ...

The Bootstrap modal backdrop is now displaying prominently in front of the modal following the latest Chrome update

Chrome version: Version 111.0.5563.64 (Official Build) (x86_64) Bootstrap: 4.3.1 Recently, there has been an issue with the modal backdrop appearing in front of the modal itself after a Chrome update. The problem does not seem to be related to z-index, an ...

What is the best way to merge two subscriptions in Angular?

Is it possible to merge the subscriptions for this.controls.attendanceDate and this.controls.type? I require simultaneous access to both in order to execute both this.isAttendanceDateOnOrAfterStartDate() and this.isAttendanceDuplicate() within the if sta ...

Encountering type errors in React+Typescript while dynamically setting values in the change handler

I am currently working on dynamically generating a form based on an array of objects. The objective is to allow users to create accounts dynamically by clicking the Add User button and then submit the complete state object of users to the backend. Encoun ...

An issue occurred during the construction of an angular project: The Tuple type '[]' with a length of '0' does not contain any elements at index '0'

When I run the command ng build --prod, I encounter the following error: ERROR in src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(5,16): Tuple type '[]' of length '0' has no element at index &apo ...

Having difficulty generating an Angular 5 Universal server application bundle with @ngtools/webpack

I am currently working on developing a cross-platform app using Angular 5 and WebPack without utilizing the CLI. The main issue I am facing is that I am unable to get the express application to function properly, resulting in encountering the following er ...

In Angular, you can easily modify and refresh an array item that is sourced from a JSON file by following these steps

Currently, I am working on implementing an edit functionality that will update the object by adding new data and deleting the old data upon updating. Specifically, I am focusing on editing and updating only the comments$. Although I am able to retrieve th ...

Acquire npm package versions by utilizing the jFrog REST API

Currently, I am attempting to retrieve the versions of an NPM package that has been published on jFrog artifactory. I know how to achieve this using a similar method with the NPM registry through the following URL: https://registry.npmjs.org/lodash Unfor ...

What is the process for implementing a unique Angular theme across all components?

I created a unique Angular theme called 'my-theme.scss' and added it to the angular.json file. While it works with most Angular Elements, I am facing issues getting it to apply to certain HTML Elements inside Angular Components. For example: < ...

Struggling to send information to the data layer on every page in Angular 9

Currently, I am in the process of integrating a GTM snippet into my Angular project. However, I have noticed that when the page is hard reloaded, it pushes data but does not do so during normal navigation. I have already added the GTM snippet provided by ...