Reza
Reza

Reputation: 19843

How to return an Observable when other observable is done

I am extending a class which already has a method which returns Observable, as below, I want to return the base observable after the result of first observable is returned (after getting token from another service),

so I develop codes like below, but typescript compiler doesn't accept because I am not returning Observeable<Response>, it will be returned in subscribe method

 post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    this.tokenService.getToken().subscribe(token => {
      //injecting token into options
      return super.post(url, body, options);
    });

}

Also I tried creating a new Observable like below, but still no chance

post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
     return new Observable<Response>(observer => {
        this.tokenService.getToken().subscribe(token => {
          //injecting token into options
          //observer.complete??? super.post(url, body, options);
        });

    });
  }

Upvotes: 1

Views: 257

Answers (1)

Brandon
Brandon

Reputation: 39192

Use flatMap to convert one observable into another observable:

post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.tokenService.getToken().flatMap(token => {
      //injecting token into options
      return super.post(url, body, options);
    });
}

Upvotes: 4

Related Questions