【问题标题】:rxjs zip two switchMap?rxjs zip 两个switchMap?
【发布时间】:2018-12-14 13:36:38
【问题描述】:

我已经定义了一个behaviorSubject:

measurementSearchChange$ = new BehaviorSubject('');
this.measurementSearchChange$
  .asObservable()
  .pipe(debounceTime(500))
  .pipe(
    switchMap((keyword: string) =>
      this.warningService.getInfluxdbQuery(
        this.selectedMonitorOption,
        'measurement',
        { search_name: keyword }
      )
    )
  )
  .subscribe((data: any) => {
    this.measurementOptions = data;
    this.isLoading = false;
  });

当一些动作时,会这样做:

this.measurementSearchChange$.next(keyword);

它现在运行良好,但我想添加一个 switchMap 并压缩它们,以便我可以订阅两个不同的数据,例如:

this.measurementSearchChange$
  .asObservable()
  .pipe(debounceTime(500))
  .pipe(
    switchMap((keyword: string) =>
      this.warningService.getInfluxdbQuery(
        this.selectedMonitorOption,
        'measurement',
        { search_name: keyword }
      )
      // another 
      this.warningService.getInfluxdbQuery2(
        this.selectedMonitorOption,
        'measurement2',
        { search_name: keyword }
      )
    )
  )
  .subscribe((data1: any, data2: any) => {
    this.measurementOptions = data;
    this.isLoading = false;
  });

那么怎么做呢?任何帮助表示感谢

【问题讨论】:

    标签: angular rxjs rxjs5 rxjs6


    【解决方案1】:

    如果您的查询发出单个结果然后完成,您可以使用forkJoin,如下所示:

    import { forkJoin } from 'rxjs';
    /* ... */
    this.measurementSearchChange$
      .asObservable()
      .pipe(
        debounceTime(500),
        switchMap((keyword: string) => forkJoin(
          this.warningService.getInfluxdbQuery(
            this.selectedMonitorOption,
            'measurement',
            { search_name: keyword }
          ),
          this.warningService.getInfluxdbQuery2(
            this.selectedMonitorOption,
            'measurement2',
            { search_name: keyword }
          )
        ))
      )
      .subscribe(([data1, data2]: [any, any]) => {
        this.measurementOptions = data;
        this.isLoading = false;
      });
    

    如果它们发出多个结果,请使用 combineLatest 而不是 forkJoin

    我不会使用zip,除非查询可以发出多个结果,并且保证每次一个查询发出一个结果时,另一个查询也会发出一个。

    【讨论】:

    • 应该是forkJoin而不是Observable.forkJoin?
    • @siva636 是的,应该是。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多