How to 'wait' for two observables in RxJS

前端 未结 7 1561
温柔的废话
温柔的废话 2020-12-13 12:14

In my app i have something like:

this._personService.getName(id)
      .concat(this._documentService.getDocument())
      .subscribe((response) => {
              


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 12:25

    Improvement of Hamid Asghari answer which use direct arguments decomposition and automatically add types (when you use typescript)

    const name$ = this._personService.getName(id);
    const document$ = this._documentService.getDocument();
    
    combineLatest([name$, document$]).subscribe(([name, document]) => {
        this.name = name;
        this.document = document;
        this.showForm();
    });

    BONUS: You can also handle errors using above approach as follows

    import { combineLatest, of } from 'rxjs';
    //...
    
    const name$ = this._personService.getName(id);
    const document$ = this._documentService.getDocument();
    
    combineLatest([
      name$.pipe(     catchError( () => of(null as string  ) ) ), 
      document$.pipe( catchError( () => of(null as Document) ) ), // 'Document' is arbitrary type
    ]).subscribe(([name, document]) => {
        this.name = name;          // or null if error
        this.document = document;  // or null if error
        this.showForm();
    });

提交回复
热议问题