简体   繁体   中英

Angular6 RxJs MergeMap call response

i am basically do one service call ( getEmp() ), along this i am do another two calls by parallelly, This works fine, but hear i need to response of the first call( getEmp()) , in below code inside return map does not return anything. Even i am add this map into the at end it return the response of getSalary() call . Thank you.

My component:
------------

getEmp.subscribe(res:any)=> {
  // Hear i need response of that getEmp() call.
}, (error: any) => {});


Service file:
-------------

public getEmp(eid: string) {
    return this.apiSvc.get('www.dld.in/employee/' + eid).pipe(
        map(res => { this.localVariable = res }), // I need the response of above call
        mergeMap(() => this.getEmpInfo(eid)),
        mergeMap(() => this.getSalary(eid)),);
}

public getEmpInfo(eid) {
   //
}

public getSalary(eid) {
   //
}

By using mergemap the way you are, the information from the first call gets assigned to this.localVariable, and then it gets discarded by the mergeMap() operators.

From the provided code there doesn't seem to be any benefit to merging the async calls in the service into one observable. I would instead suggest you return the observables from each call to your component, and then you combine it as needed in the component. Also, note that you need to pass the eid argument in the call in your component. Here is one way to do it:

Component:
------------

private emp$: Observable<any>;
private empInfo$: Observable<any>;
private empSalary$: Observable<any>;

emp$ = this.serviceName.getEmp(eid).subscribe();
empInfo$ = this.serviceName.getEmpInfo(eid).subscribe();
empSalary$ = this.serviceName.getSalary(eid).subscribe();

Service:
-------------


public getEmp(eid: string) {
    return this.apiSvc.get('www.dld.in/employee/' + eid);
}

public getEmpInfo(eid) {
   //
}

public getSalary(eid) {
   //
}

This way you are dealing with asyncronous variables in the component too, which I would recommend doing. If you instead want the value to be assigned to a non-observable in the component, you can keep the service method as I described above, and in your component you instead do:

private emp: any;

const subscription = this.serviceName.getEmp(eid).subscribe((res: any) => {
    this.emp = res;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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