0

I'm working with http requests "encapsulated" as services in my js code.

Initially, my code was a little bit spaghetti, using this way:

let user;
let business;

// check if the user is authenticated
authenticationService.isAuthenticated().subscribe(authenticated => {
    // if is authenticated
    if(authenticated) {
         // get the user profile data and save it to the user variable
         profileService.get().subscribe(data => user = data);
         // get the user business data and save it to the business variable
         businessService.get().subscribe(data => business = data);
    }
}); 

This is working, but nasty. So I rewrote the whole statement as

authenticationService.isAuthenticated()
    .pipe(
        filter(a => a), // continue only when true
        tap(() => {
            // as above, get data and save to relative variables
            this.profileService.get().subscribe(data => user = data));
            this.businessService.get().subscribe(data => business = data));
        })
     ).toPromise();

This is better, but I think there is a even better way to do this, just I don't know it.

Am I wrong?

Rob
  • 14,746
  • 28
  • 47
  • 65
Valerio
  • 3,297
  • 3
  • 27
  • 44
  • I think this question is better suited for [CodeReview](https://codereview.stackexchange.com/) – trincot Oct 28 '19 at 14:03
  • Possible duplicate of [Angular Subscribe within Subscribe](https://stackoverflow.com/questions/55447803/angular-subscribe-within-subscribe) – wentjun Oct 28 '19 at 14:38

1 Answers1

1

You already done a good job on refactoring, although there still room to make function more pure and with just outputting result and not mess with variables. Also try avoid nested subscribe

const getAuthUser=()=>authenticationService.isAuthenticated()
    .pipe(
        filter(a => a), // continue only when true
        switchMap(() => 
            zip(this.profileService.get(),
            this.businessService.get())
        }
     ).toPromise();

getAuthUser().then(([user,business])=> ......)
Fan Cheung
  • 10,745
  • 3
  • 17
  • 39