Initiate two separate asynchronous requests and send the output of the initial request as input to the subsequent one

Managing admin privileges on my website has been challenging. I store user information, including their email and admin status, in a MongoDB database. To determine if a user is an admin, I need to retrieve this information from my Python Flask API using the getUser() function. However, chaining calls between Auth0 login responses and fetching user data has proven difficult for me.

In my web.service.ts file:

getUser(email) {
        return this.http.get('http://localhost:5000/api/v1.0/user/' + email).subscribe(resp => {
            this.user_info = resp;
        });
    }

In my home.component.ts file:

export class HomeComponent { 
    constructor(private authService: AuthService,
                private webService: WebService) {}

    user_email;
    is_admin;

    ngOnInit() {

      this.authService.userProfile$.subscribe(resp => {
          if (resp != null) {
            this.user_email = resp.email
          }
      }); //Once this async call is completed, I aim to pass the user_email into the getUser() function and set the isAdmin variable based on the response.
}

Answer №1

  Using the authService user profile stream to fetch user details from the web service, and then updating the isAdmin property based on the response.

getUser(email) {
    return this.http.get('http://localhost:5000/api/v1.0/user/' + email)
} // Avoid subscribing here for better composition as shown above

By chaining operators, you can seamlessly transition data between streams. In this example, userProfile$ is mapped to getUser() using switchMap which ensures that ongoing API requests are canceled if userProfile$ emits a new value.

Answer №2

To execute your chain of commands only after receiving a response from the Auth service, you can follow this structure:

  this.authService.userProfile$.subscribe(resp => {
      if (resp != null) {
        this.user_email = resp.email;
        this.getUser(this.user_email);
      }
  });

Alternatively, you can utilize promises and await calls in combination to ensure that the code pauses until a promise is fulfilled before moving forward.

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

Is there a way to retrieve the current state of a Material UI component in a React functional component without needing to trigger an event by clicking on

Seeking a way to retrieve current values of Material Ui components without the need to click on any event after page reloads or DOM changes. These values are pulled from a database. My goal is to confirm whether the values have been updated or not by chec ...

Top recommendations for steering clear of memory leaks in Angular

In my quest to identify and resolve potential memory leaks in my angular/spartacus application, I am currently focusing on locating any instances of "subscribe(..." calls within my code base for evaluation. I understand that the simplest solution is to us ...

What could be the reason for the Angular2 Component property not appearing on my webpage?

Here is the code snippet I am working with: import {Component} from "@angular/core"; @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> <h2>{{secondTitle}}</h2> <main-page></ma ...

Webpack: The command 'webpack' does not exist as a recognized cmdlet, function, script file, or executable program

Attempting to set up a new project using webpack and typescript, I have created the project along with the webpack file. Following the instructions on the webpack website, I successfully installed webpack using npm install webpack webpack-cli --save-dev ...

Exploring the capabilities of argon2-browser in a cutting-edge setup with vite

After spending several hours attempting to implement the argon2-browser library in a Vue app with Vite, I have been encountering a persistent error. Despite following the documentation closely, I keep receiving the following message: This require call is ...

When utilizing DomSanitizer, Angular2 suddenly ceases to function properly

I've been working with Angular 2 and TypeScript. Everything was going well until I encountered an issue with my pipe, which is causing the DomSanitizer to interfere with the (click) event functionality. Even though the (click) code appears intact in ...

Encountering a TypeError while attempting to construct and launch an IOS simulator through Cordova

Currently, I am in the process of developing an Ionic app that is designed for cross-platform functionality. Encountering an Error when attempting to build and run an IOS simulator using Cordova TypeError [ERR_INVALID_ARG_TYPE]: The "code" argum ...

Is there a convenient HTML parser that is compatible with Nativescript?

I have tested various libraries like Jquery, Parse5, and JsDom, but unfortunately they are not compatible with nativescript. Jquery relies on the DOM, while Parse5 and JsDom require Node.js which is currently not supported by nativescript. I am in need of ...

What is the process for utilizing the TypeScript compiler with nodejs?

I have a sample code saved in a file called hello.ts Upon the completion of nodejs setup on Windows, execute the following command to install typescript: npm install -g typescript Is there a way to compile hello.ts directly with node.js? While using "T ...

Ways to troubleshoot and resolve the npx create-next-app issue

Every time I try to create a new app using npx create-next-app@latest --typescript, it keeps giving me this error message: npm ERR! code ENETUNREACH npm ERR! syscall connect npm ERR! errno ENETUNREACH npm ERR! request to https://registry.npmjs.org/create-n ...

Error in Redux reducer file caused by an incorrect data type in action.payload

I have encountered a type error in my reducers' file where it says that my 'Property 'address' does not exist on type 'number | { connection: boolean; address: string; }'. This issue is arising in my React application while us ...

rxjs in Angular2 is missing the observable.interval function

Currently, I am attempting to utilize the interval method of an observable; however, I consistently encounter the following error message: Property 'interval' does not exist on type 'Observable<any>'. I have included the follow ...

Achieving successful npm caching in Azure DevOps for a .net core Angular project

I have a project for a client that involves building an Angular 10/.Net Core project, and it currently takes around 15 minutes. I've been experimenting with caching to optimize the process. Despite trying different configurations, when I add eq(variab ...

Issue with retrieving properties in Angular template due to undefined values in HTML

As a newbie to Angular, I am dedicated to improving my skills in the framework. In my project, I am utilizing three essential files: a service (Studentservice.ts) that emits an observable through the ShowBeerDetails method, and then I subscribe to this ob ...

Trouble accessing data property within a method in Vue 3 with Typescript

I am facing an issue with accessing my data in a method I have written. I am getting a Typescript error TS2339 which states that the property does not exist in the type. TS2339: Property 'players' does not exist on type '{ onAddPlayers(): vo ...

When the route changes, routerCanReuse and routerOnReuse are not invoked

I am currently exploring the functionalities of Angular2's Router, specifically focusing on OnReuse and CanReuse. I have followed the documentation provided here, but I seem to be encountering difficulties in getting the methods to trigger when the ro ...

Unable to translate text on the loading page

Encountering a peculiar issue with the translate service. Here's how I set it up: export class AppComponent implements OnInit { constructor( private translateService: TranslateService, angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics ...

Are generic constraints leading to type inference selecting the incorrect candidate?

TypeScript Version: 2.6.0-dev.20170826 and 2.4.2 I'm questioning whether I've encountered a TypeScript inference bug or limitation, or if my code is simply incorrect. If the code is valid and it's an issue with type inference, I will repor ...

Utilize Type Script/Angular 8 for seamless file management by either dragging and dropping files or selecting

Can you provide guidance on using the ng-upload-file plugin with TypeScript? https://github.com/danialfarid/ng-file-upload I attempted to implement it but encountered difficulties. Do you have a working sample available or know of another open-source plu ...

What are the advantages of using interfaces in React?

Exploring Typescript's interface and its application in React has been an interesting journey for me. It seems that interfaces are used to define specific props that can be passed, acting as a form of protection against passing irrelevant props. My qu ...