简体   繁体   English

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

[英]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: 我对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();
  }

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? 我将其余所需的代码包装在this.facade.getConfig.subscribe((config: AppConfig) => {如您所见,是否可以像我对标头和jwt令牌那样使用高阶可观察的运算符来简化此代码?

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)
    )
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM