Reputation: 189
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'
//}
Upvotes: 0
Views: 2037
Reputation: 58039
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. Then return a jorkJoin of the union of the response and this.getEmpDetails. Finally you map the result to get an uniqe object with the properties of both
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]}}))
Upvotes: 4
Reputation: 476
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
Hope it help.
Upvotes: 1