【问题标题】:concatMap vs. switchMap when observable only returns one value in Angular可观察时 concatMap 与 switchMap 在 Angular 中仅返回一个值
【发布时间】:2022-10-15 03:41:06
【问题描述】:

当一个可观察对象返回多个值时,我得到了 concatMap 和 switchMap 之间的区别。然而,当所有的 observables 只返回一个值时,使用一个比另一个有什么优势吗?这是一个在构造函数中调用完全相同的示例,一个使用 concatMap,一个使用 switchMap。在这种情况下,要么优先于另一个?

import { Component } from '@angular/core';
import { concatMap, forkJoin, Observable, of, switchMap } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  var1: any[];
  var2: any[];
  detailVar: any;


  func1(): Observable<any[]> {
    return of([
      { id: 1, value: 'One' },
      { id: 2, value: 'Two' },
      { id: 3, value: 'Three' }
    ])
  }

  func2(): Observable<any[]> {
    return of([
      { id: 4, value: 'Four' },
      { id: 5, value: 'Five' },
      { id: 6, value: 'Six' }
    ])
  }

  funcDetail(): Observable<any> {
    return of(
      { id: 1, name: 'name', oneId: 2, twoId: 5 }
    )
  }

  constructor() {

    // concatMap


    this.funcDetail().pipe(concatMap((data) => {
      this.detailVar = data;
      return forkJoin([
        this.func1(),
        this.func2()
      ])
    }
    )).subscribe((dds) => {
      this.var1 = dds[0];
      this.var2 = dds[1];

      console.log(this.detailVar);
      console.log(this.var1);
      console.log(this.var2);
    });


    // switchMap

    this.funcDetail().pipe(switchMap((data) => {
      this.detailVar = data;
      return forkJoin([
        this.func1(),
        this.func2()
      ])
    }
    )).subscribe((dds) => {
      this.var1 = dds[0];
      this.var2 = dds[1];

      console.log(this.detailVar);
      console.log(this.var1);
      console.log(this.var2);
    });


  }


}

【问题讨论】:

    标签: angular rxjs rxjs-observables angular-observable


    【解决方案1】:
    switchMap:
    
    this.func1().pipe(
      switchMap(response => {
        this.var1 = response;
        return this.func2();
      }),
      switchMap(response => {
        this.var2 = response;
        return this.funcDetail();
      })
    ).subscribe(response => {
      this.detailVar = response;
    })
    
    concatMap:
    
    this.func1().pipe(
      concatMap(response => {
        this.var1 = response;
        return this.func2();
      }),
      concatMap(response => {
        this.var2 = response;
        return this.funcDetail();
      })
    ).subscribe(response => {
      this.detailVar = response;
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 2012-08-02
      • 1970-01-01
      相关资源
      最近更新 更多