RxJS-如何使用mergemap或map简化可观察的订阅

时间:2019-02-17 02:02:42

标签: angular typescript rxjs

我有一个对api的通用http请求,但是首先我从ngrx存储中获取了apiUrl,这是可以观察到的,因此我可以将其应用于我的http请求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();
  }

如您所见,我将其余所需的代码包装在this.facade.getConfig.subscribe((config: AppConfig) => {内。我可以像对标头和jwt令牌那样使用高阶可观察的运算符来简化此操作吗?

1 个答案:

答案 0 :(得分:2)

这是您如何在一个级别上进行选择

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)
    )
  );
}
相关问题