代码之家  ›  专栏  ›  技术社区  ›  rmcsharry

Angular 9 rxJs-如何使用combine/merge语句检索可观察值并传递给另一个函数

  •  0
  • rmcsharry  · 技术社区  · 6 年前

    我有一个服务让我打开一个陷阱:

    this.snackBarService.open(title, body);
    

    title body 是弦。

    我的问题是,它们都需要从密钥进行翻译,而翻译服务返回一个可观察到的:

      /**
       * Returns an observable for a translation based on the key
       *
       * @param key the translation key
       */
      private getTranslation(key: string): Observable<string> {
        return this.translocoService.selectTranslate(key, {}, 'auth');
      }
    

    This question 让我觉得我可以用 mergeMap combineLatest 在调用open方法之前,如下所示:

      this.getTranslation('snackbars.username.success.title').pipe(
        mergeMap(title => {
          return combineLatest(
            of(title),
            this.getTranslation('snackbars.username.success.body')
          );
        }),
        map(([title, body]) => {
          console.log('here', title, body);
          this.snackBarService.open(title, body);
        })
      );
    

    但什么也没发生…控制台什么都不记录:(

    订阅和取消订阅这两个getTranslation调用会有点乏味……那么,有什么简单的方法可以从可观测值中获取值并将它们传递给snackbar呢?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Michael D    6 年前

    我相信你只要一个 forkJoin . 尝试以下操作

    forkJoin([
      this.getTranslation('snackbars.username.success.title'), 
      this.getTranslation('snackbars.username.success.body')
    ]).subscribe(
      response => {
        console.log('here', response[0], response[1]);
        this.snackBarService.open(response[0], response[1]);
      }
    );
    

    叉接 只有当两个观测都完成时才发射。如果没有,你可以用 combineLatest 在一个 take(1) 仅使用从可观测数据中发出的第一个值并完成。

    combineLatest([
      this.getTranslation('snackbars.username.success.title'), 
      this.getTranslation('snackbars.username.success.body')
    ]).pipe(
        take(1)
      ).subscribe(
      response => {
        console.log('here', response[0], response[1]);
        this.snackBarService.open(response[0], response[1]);
      }
    );