sensei
sensei

Reputation: 7592

RxJS - how to simplify observable subscription with mergemap or map

I have a generic http request to api, but first I am getting apiUrl from my ngrx store which is observable, so I can apply it to my http request url:

  /**
   * Get API wrapper
   * @param endpoint The endpoint you want to call;
   * @param params The params you want to pass in
   */
  public get<T>(endpoint: string, params?: HttpParams): Observable<T> {
    this.facade.getConfig.subscribe((config: AppConfig) => {
      return this.authenticationService.GetToken().pipe(
        map((jwt: string) => ({
          headers: new HttpHeaders().set('Authorization', `Bearer ${jwt}`),
          params: params
        })),
        mergeMap((options: { headers: HttpHeaders; params: HttpParams }) =>
          this.http.get<T>(config.AppSettings.ApiUrl + endpoint, options)
        )
      );
    });

    return of();
  }

I wrapped rest of the required code inside of this.facade.getConfig.subscribe((config: AppConfig) => { as you can see. Can I simplify this with higher order observable operators like i did it for headers and jwt token?

Upvotes: 1

Views: 309

Answers (1)

Fan Cheung
Fan Cheung

Reputation: 11380

this is how you can chhain them on one level

public get<T>(endpoint: string, params ?: HttpParams): Observable < T > {
  return this.facade.getConfig.pipe(
    mergeMap((config: AppConfig) => this.authenticationService.GetToken())
    map((jwt: string) => ({
      headers: new HttpHeaders().set('Authorization', `Bearer ${jwt}`),
      params: params
    })),
    mergeMap((options: { headers: HttpHeaders; params: HttpParams }) =>
      this.http.get<T>(config.AppSettings.ApiUrl + endpoint, options)
    )
  );
}

Upvotes: 2

Related Questions