0

I have a site using Auth0, to determine if a user is an admin I store a field in my mongoDB database for that user accompanied by their associated email which I read back from my python flask API endpoint in the getUser() function. When the user logs in I receive the response of Auth0 user email and pass the relevant field into the getUser() function, however, I'm having trouble coming up with a solution to chain these calls. So far I've tried using promises and subscriptions but to no avail.

web.service.ts

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

home.component.ts

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
          }
      }); //after this aync call is completed, I want to pass the user_email into the getUser()
          //function and set is_admin depending on the response
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
mrrain
  • 134
  • 1
  • 12

2 Answers2

1
  this.authService.userProfile$.pipe(switchMap((resp) => this.webService.getUser(resp.email))).subscribe((resp) => {
    this.is_admin = resp.is_admin;
  });

  getUser(email) {
    return this.http.get('http://localhost:5000/api/v1.0/user/' + email)
  } // Dont subscribe here to compose as done above

You can always compose from one stream to another using operators. Here I am mapping userProfile$ stream to getUser() stream. I am using switchMap operator here which will cancel getUser method if your userProfile$ stream emits value while the api is in progress state.

Siddharth Pal
  • 1,408
  • 11
  • 23
-2

You could perform your chain after you get a response back from the Auth service: i.e.:

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

Or use a combination of promises and await calls so the code will await until a promise is resolved before continuing forward

NiallMitch14
  • 1,198
  • 1
  • 12
  • 28