简体   繁体   English

结合两个可观察到的嵌套可观察角度?

[英]combine two observables in nested observable in angular?

How to combine two observable and return new observable where second one is depends on value of first one. 如何合并两个可观察值并在第二个可观察值返回时返回新的可观察值取决于第一个可观察值。 here I'm expecting new object which is combination of few values of first one and few values of second one. 在这里,我期待一个新对象,它是第一个的几个值和第二个的几个值的组合。

export interface EmpData {
  id: number;
  name: string;
}

export const EMPDATA: EmpData = {
    id : 11, name : 'xyz'
};

 export interface EmpDetails {
  id: number;
  desiganation: string;
}

export const EMPDATAILS: EmpDetails = {
    id : 11, desiganation : 'manager'
};

  getEmpData(name: string): Observable<EmpData> {
   // search based on name and return object 
   // temporary returning some data
    return of(EMPDATA);
  }

  getEmpDetails(id: number): Observable<EmpDetails> {
  // search based on id and return object 
   // temporary returning some data
    return of(EMPDATAILS);
  }

  getEmploye(name: string): Observable<any> {
    return this.getEmpData(name).pipe(
      flatMap((response) => {
        return this.getEmpDetails(response.id);
    );
  });

 this.getEmploye(xyz).subscribe(response =>
     // here I'm expecting response as below, i.e. combination of first and 
     //second observable
      //{ 
      //  id: 11,name:'XYZ', desiganation : 'manager'
      //}
getEmploye(name: string): Observable<any> 
{
    return this.getEmpData(name).pipe(
      switchMap((response) => {
        return forkJoin(of(response),this.getEmpDetails(response.id);
    ),
    map(res=>{return {...res[0],...res[1]}}))
}

You get this.getEmpData. 您得到this.getEmpData。 Then return a jorkJoin of the union of the response and this.getEmpDetails. 然后返回响应和this.getEmpDetails的并集的jorkJoin。 Finally you map the result to get an uniqe object with the properties of both 最后,将结果映射为具有两个属性的uniqe对象

NOTE: if you want to have separate the main and the detail data the last map can be like 注意:如果您希望将主要数据和详细数据分开,则最后一张地图可以像

map(res=>{return {...res[0],detail:res[1]}}))

You can use 您可以使用

Observable.forkJoin

Also in this file of best angular boilerplate project i can show you, how to use it: Link to usage in ngir project 另外,在此最佳角度样板项目文件中,我可以向您展示如何使用它: 链接到ngir项目中的用法

Hope it help. 希望对您有所帮助。

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

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