velouriam
velouriam

Reputation: 21

Angular 5 chain service observables then return observable to component

I have two rest calls I need to make. Rest call 2 depends on rest call 1. And I want to store each result in the service before proceeding. Then I want to return an observable to the component that calls rest call 1 so the component can subscribe in case of issues.

code from service:

login(username: string, password: string): Observable<AuthAccess> {
// rest call 1
return this.getAuthClient()
  .flatMap(res => {
    this.client = res.body;
    // rest call 2
    return this.authenticate(username, password)
      .flatMap(access => {
        this.userAccess = access.body;
        return Observable.of(this.userAccess);
      });
  });

}

I can get this to chain correctly, but the component that is calling this and subscribing to the call will show an undefined response. Any help on this would be greatly appreciated as I cannot find responses on this exact use case.

Upvotes: 0

Views: 1519

Answers (1)

Luillyfe
Luillyfe

Reputation: 6842

Live working example. Use a map operator (and the lettable operatos sintax), instead of chain a new flatMap.

login(username: string, password: string): Observable<any> {
      // rest call 1
      return this.getAuthClient()
          .pipe(flatMap(res => {
              this.client = res.body;
              // rest call 2
              return this.authenticate(username, password)
                  .pipe(map(access => {
                      this.userAccess = access.body;
                      return this.userAccess;
                  }));
          }));
  }

Upvotes: 5

Related Questions