Angular 6: How to make a set of service calls in parallel and process Data once all of them are completed












2















I am working on Angular 6+ web-app using rxjs 6+ .



There is a set of services(all are different and make different http calls) .
Basically these services are used to initialize the app.



My requirement is to call these services in parallel and wait untill all of them are finished . Once finished , I need to process the responses received .
I have studied a lot on this and found that forkJoin and combineLatest can be my friend.
And i have implemented the same in the following way :



 getInitialData() {

this._authService.openCorsConnection().subscribe(res => {
forkJoin(
this._authService.x(),
this._tService.getSystemDate(),
this._tService.getTemp(),
this._tService.getSettings()
).pipe(
catchError( err => {
console.log('gor error',err);
if (err.status == 401) {
// this._router.navigateByUrl('/unauthorize');
return EMPTY;
} else {
return throwError(err);
}
}),
map(([x,y,z,p])=>{
console.log('sucesss',{x,y,z,p});
return {x,y,z,p}
}),
finalize(()=>{
console.log('Executing Finally');
processData();

})
);
});
}


But These are not executing . Here are the services :



x(): Observable<any> {          
const xUrl = EnvironmentConfiguration.endPointConfig.xServiceEndpoint;
let serviceMethod: String = 'x';
let requestObj: any = this._utilHelperSvc.getRequestObject(xUrl , { "y": "" }, serviceMethod);
return this._http.post<any>(requestObj.url,{ "pid": "" } , requestObj)
.pipe(
catchError(this.handleError('x', {}))
);
}


Do i need to modify services ?
I am not able to figure out how to solve this.



Can anybody please Suggest some better solution or different approach for this ?



Thanks.










share|improve this question

























  • Have you try replacing forkJoin with combineLatest? Did that work?

    – YGLin
    Nov 2 '18 at 10:02











  • @YGLin yes.. both are behaving in the same way. Even if a write subscribe on services, the forkJoin's callbacks are not executing...

    – programoholic
    Nov 2 '18 at 10:05











  • I noticed that you have 2-level of subscribe, are you sure the first one, openCorsConnection(), emit as expected? If so, maybe you need to check those service calls one by one to make sure each emit successfully. Can't help you much further, sorry~

    – YGLin
    Nov 2 '18 at 10:26











  • If forkJoin doesn't emit any value then one of you source Observables doesn't emit anything or doesn't complete

    – martin
    Nov 2 '18 at 10:50
















2















I am working on Angular 6+ web-app using rxjs 6+ .



There is a set of services(all are different and make different http calls) .
Basically these services are used to initialize the app.



My requirement is to call these services in parallel and wait untill all of them are finished . Once finished , I need to process the responses received .
I have studied a lot on this and found that forkJoin and combineLatest can be my friend.
And i have implemented the same in the following way :



 getInitialData() {

this._authService.openCorsConnection().subscribe(res => {
forkJoin(
this._authService.x(),
this._tService.getSystemDate(),
this._tService.getTemp(),
this._tService.getSettings()
).pipe(
catchError( err => {
console.log('gor error',err);
if (err.status == 401) {
// this._router.navigateByUrl('/unauthorize');
return EMPTY;
} else {
return throwError(err);
}
}),
map(([x,y,z,p])=>{
console.log('sucesss',{x,y,z,p});
return {x,y,z,p}
}),
finalize(()=>{
console.log('Executing Finally');
processData();

})
);
});
}


But These are not executing . Here are the services :



x(): Observable<any> {          
const xUrl = EnvironmentConfiguration.endPointConfig.xServiceEndpoint;
let serviceMethod: String = 'x';
let requestObj: any = this._utilHelperSvc.getRequestObject(xUrl , { "y": "" }, serviceMethod);
return this._http.post<any>(requestObj.url,{ "pid": "" } , requestObj)
.pipe(
catchError(this.handleError('x', {}))
);
}


Do i need to modify services ?
I am not able to figure out how to solve this.



Can anybody please Suggest some better solution or different approach for this ?



Thanks.










share|improve this question

























  • Have you try replacing forkJoin with combineLatest? Did that work?

    – YGLin
    Nov 2 '18 at 10:02











  • @YGLin yes.. both are behaving in the same way. Even if a write subscribe on services, the forkJoin's callbacks are not executing...

    – programoholic
    Nov 2 '18 at 10:05











  • I noticed that you have 2-level of subscribe, are you sure the first one, openCorsConnection(), emit as expected? If so, maybe you need to check those service calls one by one to make sure each emit successfully. Can't help you much further, sorry~

    – YGLin
    Nov 2 '18 at 10:26











  • If forkJoin doesn't emit any value then one of you source Observables doesn't emit anything or doesn't complete

    – martin
    Nov 2 '18 at 10:50














2












2








2


2






I am working on Angular 6+ web-app using rxjs 6+ .



There is a set of services(all are different and make different http calls) .
Basically these services are used to initialize the app.



My requirement is to call these services in parallel and wait untill all of them are finished . Once finished , I need to process the responses received .
I have studied a lot on this and found that forkJoin and combineLatest can be my friend.
And i have implemented the same in the following way :



 getInitialData() {

this._authService.openCorsConnection().subscribe(res => {
forkJoin(
this._authService.x(),
this._tService.getSystemDate(),
this._tService.getTemp(),
this._tService.getSettings()
).pipe(
catchError( err => {
console.log('gor error',err);
if (err.status == 401) {
// this._router.navigateByUrl('/unauthorize');
return EMPTY;
} else {
return throwError(err);
}
}),
map(([x,y,z,p])=>{
console.log('sucesss',{x,y,z,p});
return {x,y,z,p}
}),
finalize(()=>{
console.log('Executing Finally');
processData();

})
);
});
}


But These are not executing . Here are the services :



x(): Observable<any> {          
const xUrl = EnvironmentConfiguration.endPointConfig.xServiceEndpoint;
let serviceMethod: String = 'x';
let requestObj: any = this._utilHelperSvc.getRequestObject(xUrl , { "y": "" }, serviceMethod);
return this._http.post<any>(requestObj.url,{ "pid": "" } , requestObj)
.pipe(
catchError(this.handleError('x', {}))
);
}


Do i need to modify services ?
I am not able to figure out how to solve this.



Can anybody please Suggest some better solution or different approach for this ?



Thanks.










share|improve this question
















I am working on Angular 6+ web-app using rxjs 6+ .



There is a set of services(all are different and make different http calls) .
Basically these services are used to initialize the app.



My requirement is to call these services in parallel and wait untill all of them are finished . Once finished , I need to process the responses received .
I have studied a lot on this and found that forkJoin and combineLatest can be my friend.
And i have implemented the same in the following way :



 getInitialData() {

this._authService.openCorsConnection().subscribe(res => {
forkJoin(
this._authService.x(),
this._tService.getSystemDate(),
this._tService.getTemp(),
this._tService.getSettings()
).pipe(
catchError( err => {
console.log('gor error',err);
if (err.status == 401) {
// this._router.navigateByUrl('/unauthorize');
return EMPTY;
} else {
return throwError(err);
}
}),
map(([x,y,z,p])=>{
console.log('sucesss',{x,y,z,p});
return {x,y,z,p}
}),
finalize(()=>{
console.log('Executing Finally');
processData();

})
);
});
}


But These are not executing . Here are the services :



x(): Observable<any> {          
const xUrl = EnvironmentConfiguration.endPointConfig.xServiceEndpoint;
let serviceMethod: String = 'x';
let requestObj: any = this._utilHelperSvc.getRequestObject(xUrl , { "y": "" }, serviceMethod);
return this._http.post<any>(requestObj.url,{ "pid": "" } , requestObj)
.pipe(
catchError(this.handleError('x', {}))
);
}


Do i need to modify services ?
I am not able to figure out how to solve this.



Can anybody please Suggest some better solution or different approach for this ?



Thanks.







angular rxjs observable angular6 rxjs6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 23:04







programoholic

















asked Nov 2 '18 at 9:28









programoholicprogramoholic

5321527




5321527













  • Have you try replacing forkJoin with combineLatest? Did that work?

    – YGLin
    Nov 2 '18 at 10:02











  • @YGLin yes.. both are behaving in the same way. Even if a write subscribe on services, the forkJoin's callbacks are not executing...

    – programoholic
    Nov 2 '18 at 10:05











  • I noticed that you have 2-level of subscribe, are you sure the first one, openCorsConnection(), emit as expected? If so, maybe you need to check those service calls one by one to make sure each emit successfully. Can't help you much further, sorry~

    – YGLin
    Nov 2 '18 at 10:26











  • If forkJoin doesn't emit any value then one of you source Observables doesn't emit anything or doesn't complete

    – martin
    Nov 2 '18 at 10:50



















  • Have you try replacing forkJoin with combineLatest? Did that work?

    – YGLin
    Nov 2 '18 at 10:02











  • @YGLin yes.. both are behaving in the same way. Even if a write subscribe on services, the forkJoin's callbacks are not executing...

    – programoholic
    Nov 2 '18 at 10:05











  • I noticed that you have 2-level of subscribe, are you sure the first one, openCorsConnection(), emit as expected? If so, maybe you need to check those service calls one by one to make sure each emit successfully. Can't help you much further, sorry~

    – YGLin
    Nov 2 '18 at 10:26











  • If forkJoin doesn't emit any value then one of you source Observables doesn't emit anything or doesn't complete

    – martin
    Nov 2 '18 at 10:50

















Have you try replacing forkJoin with combineLatest? Did that work?

– YGLin
Nov 2 '18 at 10:02





Have you try replacing forkJoin with combineLatest? Did that work?

– YGLin
Nov 2 '18 at 10:02













@YGLin yes.. both are behaving in the same way. Even if a write subscribe on services, the forkJoin's callbacks are not executing...

– programoholic
Nov 2 '18 at 10:05





@YGLin yes.. both are behaving in the same way. Even if a write subscribe on services, the forkJoin's callbacks are not executing...

– programoholic
Nov 2 '18 at 10:05













I noticed that you have 2-level of subscribe, are you sure the first one, openCorsConnection(), emit as expected? If so, maybe you need to check those service calls one by one to make sure each emit successfully. Can't help you much further, sorry~

– YGLin
Nov 2 '18 at 10:26





I noticed that you have 2-level of subscribe, are you sure the first one, openCorsConnection(), emit as expected? If so, maybe you need to check those service calls one by one to make sure each emit successfully. Can't help you much further, sorry~

– YGLin
Nov 2 '18 at 10:26













If forkJoin doesn't emit any value then one of you source Observables doesn't emit anything or doesn't complete

– martin
Nov 2 '18 at 10:50





If forkJoin doesn't emit any value then one of you source Observables doesn't emit anything or doesn't complete

– martin
Nov 2 '18 at 10:50












2 Answers
2






active

oldest

votes


















2














TL;DR



Use zip or forkjoin.



Demos :




  • Demo with forkJoin

  • Demo with zip


Explanation



You don't need to wait for forkJoin to process the responses, it works the other way around. Instead, prepare all the jobs that need to be done, and simply wait for completion.



Here is what I mean:



let process1$ = timer(1000);
let process2$ = timer(2000);
let process3$ = timer(3000);

const doSthg1 = pipe(
tap(() => console.log('Process 1 has finished')),
map(() => 'Process 1 has finished')
)

const doSthg2 = pipe(
tap(() => console.log('Process 2 has finished')),
map(() => 'Process 2 has finished')
)

const doSthg3 = pipe(
tap(() => console.log('Process 3 has finished')),
map(() => 'Process 3 has finished')
)

forkJoin(doSthg1(process1$), doSthg2(process2$), doSthg3(process3$)).subscribe(() => {
console.log('Now I am complete');
});


Demo with forkJoin



This works as long as your processes are not chained, i.e the input of one does not depend on the output of another.



why isn't my code working ?



Because you don't actually subscribe to forkJoin.
Solution : for example, you can use concatMap to transform this._authService.openCorsConnection() into another Observable :



getInitialData(){
this._authService.openCorsConnection().pipe(
concatMap(() => forkJoin(this._authService.x(),
this._tService.getSystemDate(),
this._tService.getTemp(),
this._tService.getSettings()
)),
catchError(err => {
console.log('gor error', err);
if (err.status == 401) {
return EMPTY;
} else {
return throwError(err);
}
}),
).subscribe(() => processData());
}


zip



You could use zip instead of forkJoin if:




  1. all processes emit only once, then complete : for example http Get or Post requests.

  2. you want to get join outputs from your sources.


implementation:



zip(doSthg1(process1$), doSthg2(process2$), doSthg3(process3$))
.subscribe(
([x,y,z]) => {
console.log(`x=${x}, y=${y}, z=${z}`);
});


Demo with zip






share|improve this answer


























  • @madjaous Thanks.. i will try this... Also i have updated the service body in my question. can you pls tell if any modification is required ?

    – programoholic
    Nov 2 '18 at 11:36











  • yes i need to process data for each service . I am not sure "do all your services emit once" means but yes.. all service returns data for sure.

    – programoholic
    Nov 2 '18 at 11:52











  • Thanks buddy.. Will let you know once i implement.

    – programoholic
    Nov 3 '18 at 16:35






  • 1





    It works perfectly .....

    – programoholic
    Nov 6 '18 at 9:43



















0














I have just do few days ago after lot's of search.



The main thing is how you call list of API.



If you call API from component.ts then you got data in that. The twist is when you call API by service the you have to store the reference of API call.



I have done this by this way...



var pendingAPIList : any = ;


you can add API list in array with ref of observable.



return new Observable(observer => {
var obj = {
url:url,
param:param,
ref : observer // <-- Hear is the main trick
}
this.pendingAPIList.push(obj); // Add multiple API in array
})


When all API added then call then...



Observable.forkJoin(this.pendingAPIList).subscribe(response){

// You will get data in array
// Now return all API res in their subscribers at .ts file...

for(let i = 0 ; i < this.pendingAPIList.lengh ; i++ ){
this.pendingAPIList[i].ref.next(response[i]);
this.pendingAPIList[i].ref.complete();
}
}


This is working fine for me... :)






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53115864%2fangular-6-how-to-make-a-set-of-service-calls-in-parallel-and-process-data-once%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    TL;DR



    Use zip or forkjoin.



    Demos :




    • Demo with forkJoin

    • Demo with zip


    Explanation



    You don't need to wait for forkJoin to process the responses, it works the other way around. Instead, prepare all the jobs that need to be done, and simply wait for completion.



    Here is what I mean:



    let process1$ = timer(1000);
    let process2$ = timer(2000);
    let process3$ = timer(3000);

    const doSthg1 = pipe(
    tap(() => console.log('Process 1 has finished')),
    map(() => 'Process 1 has finished')
    )

    const doSthg2 = pipe(
    tap(() => console.log('Process 2 has finished')),
    map(() => 'Process 2 has finished')
    )

    const doSthg3 = pipe(
    tap(() => console.log('Process 3 has finished')),
    map(() => 'Process 3 has finished')
    )

    forkJoin(doSthg1(process1$), doSthg2(process2$), doSthg3(process3$)).subscribe(() => {
    console.log('Now I am complete');
    });


    Demo with forkJoin



    This works as long as your processes are not chained, i.e the input of one does not depend on the output of another.



    why isn't my code working ?



    Because you don't actually subscribe to forkJoin.
    Solution : for example, you can use concatMap to transform this._authService.openCorsConnection() into another Observable :



    getInitialData(){
    this._authService.openCorsConnection().pipe(
    concatMap(() => forkJoin(this._authService.x(),
    this._tService.getSystemDate(),
    this._tService.getTemp(),
    this._tService.getSettings()
    )),
    catchError(err => {
    console.log('gor error', err);
    if (err.status == 401) {
    return EMPTY;
    } else {
    return throwError(err);
    }
    }),
    ).subscribe(() => processData());
    }


    zip



    You could use zip instead of forkJoin if:




    1. all processes emit only once, then complete : for example http Get or Post requests.

    2. you want to get join outputs from your sources.


    implementation:



    zip(doSthg1(process1$), doSthg2(process2$), doSthg3(process3$))
    .subscribe(
    ([x,y,z]) => {
    console.log(`x=${x}, y=${y}, z=${z}`);
    });


    Demo with zip






    share|improve this answer


























    • @madjaous Thanks.. i will try this... Also i have updated the service body in my question. can you pls tell if any modification is required ?

      – programoholic
      Nov 2 '18 at 11:36











    • yes i need to process data for each service . I am not sure "do all your services emit once" means but yes.. all service returns data for sure.

      – programoholic
      Nov 2 '18 at 11:52











    • Thanks buddy.. Will let you know once i implement.

      – programoholic
      Nov 3 '18 at 16:35






    • 1





      It works perfectly .....

      – programoholic
      Nov 6 '18 at 9:43
















    2














    TL;DR



    Use zip or forkjoin.



    Demos :




    • Demo with forkJoin

    • Demo with zip


    Explanation



    You don't need to wait for forkJoin to process the responses, it works the other way around. Instead, prepare all the jobs that need to be done, and simply wait for completion.



    Here is what I mean:



    let process1$ = timer(1000);
    let process2$ = timer(2000);
    let process3$ = timer(3000);

    const doSthg1 = pipe(
    tap(() => console.log('Process 1 has finished')),
    map(() => 'Process 1 has finished')
    )

    const doSthg2 = pipe(
    tap(() => console.log('Process 2 has finished')),
    map(() => 'Process 2 has finished')
    )

    const doSthg3 = pipe(
    tap(() => console.log('Process 3 has finished')),
    map(() => 'Process 3 has finished')
    )

    forkJoin(doSthg1(process1$), doSthg2(process2$), doSthg3(process3$)).subscribe(() => {
    console.log('Now I am complete');
    });


    Demo with forkJoin



    This works as long as your processes are not chained, i.e the input of one does not depend on the output of another.



    why isn't my code working ?



    Because you don't actually subscribe to forkJoin.
    Solution : for example, you can use concatMap to transform this._authService.openCorsConnection() into another Observable :



    getInitialData(){
    this._authService.openCorsConnection().pipe(
    concatMap(() => forkJoin(this._authService.x(),
    this._tService.getSystemDate(),
    this._tService.getTemp(),
    this._tService.getSettings()
    )),
    catchError(err => {
    console.log('gor error', err);
    if (err.status == 401) {
    return EMPTY;
    } else {
    return throwError(err);
    }
    }),
    ).subscribe(() => processData());
    }


    zip



    You could use zip instead of forkJoin if:




    1. all processes emit only once, then complete : for example http Get or Post requests.

    2. you want to get join outputs from your sources.


    implementation:



    zip(doSthg1(process1$), doSthg2(process2$), doSthg3(process3$))
    .subscribe(
    ([x,y,z]) => {
    console.log(`x=${x}, y=${y}, z=${z}`);
    });


    Demo with zip






    share|improve this answer


























    • @madjaous Thanks.. i will try this... Also i have updated the service body in my question. can you pls tell if any modification is required ?

      – programoholic
      Nov 2 '18 at 11:36











    • yes i need to process data for each service . I am not sure "do all your services emit once" means but yes.. all service returns data for sure.

      – programoholic
      Nov 2 '18 at 11:52











    • Thanks buddy.. Will let you know once i implement.

      – programoholic
      Nov 3 '18 at 16:35






    • 1





      It works perfectly .....

      – programoholic
      Nov 6 '18 at 9:43














    2












    2








    2







    TL;DR



    Use zip or forkjoin.



    Demos :




    • Demo with forkJoin

    • Demo with zip


    Explanation



    You don't need to wait for forkJoin to process the responses, it works the other way around. Instead, prepare all the jobs that need to be done, and simply wait for completion.



    Here is what I mean:



    let process1$ = timer(1000);
    let process2$ = timer(2000);
    let process3$ = timer(3000);

    const doSthg1 = pipe(
    tap(() => console.log('Process 1 has finished')),
    map(() => 'Process 1 has finished')
    )

    const doSthg2 = pipe(
    tap(() => console.log('Process 2 has finished')),
    map(() => 'Process 2 has finished')
    )

    const doSthg3 = pipe(
    tap(() => console.log('Process 3 has finished')),
    map(() => 'Process 3 has finished')
    )

    forkJoin(doSthg1(process1$), doSthg2(process2$), doSthg3(process3$)).subscribe(() => {
    console.log('Now I am complete');
    });


    Demo with forkJoin



    This works as long as your processes are not chained, i.e the input of one does not depend on the output of another.



    why isn't my code working ?



    Because you don't actually subscribe to forkJoin.
    Solution : for example, you can use concatMap to transform this._authService.openCorsConnection() into another Observable :



    getInitialData(){
    this._authService.openCorsConnection().pipe(
    concatMap(() => forkJoin(this._authService.x(),
    this._tService.getSystemDate(),
    this._tService.getTemp(),
    this._tService.getSettings()
    )),
    catchError(err => {
    console.log('gor error', err);
    if (err.status == 401) {
    return EMPTY;
    } else {
    return throwError(err);
    }
    }),
    ).subscribe(() => processData());
    }


    zip



    You could use zip instead of forkJoin if:




    1. all processes emit only once, then complete : for example http Get or Post requests.

    2. you want to get join outputs from your sources.


    implementation:



    zip(doSthg1(process1$), doSthg2(process2$), doSthg3(process3$))
    .subscribe(
    ([x,y,z]) => {
    console.log(`x=${x}, y=${y}, z=${z}`);
    });


    Demo with zip






    share|improve this answer















    TL;DR



    Use zip or forkjoin.



    Demos :




    • Demo with forkJoin

    • Demo with zip


    Explanation



    You don't need to wait for forkJoin to process the responses, it works the other way around. Instead, prepare all the jobs that need to be done, and simply wait for completion.



    Here is what I mean:



    let process1$ = timer(1000);
    let process2$ = timer(2000);
    let process3$ = timer(3000);

    const doSthg1 = pipe(
    tap(() => console.log('Process 1 has finished')),
    map(() => 'Process 1 has finished')
    )

    const doSthg2 = pipe(
    tap(() => console.log('Process 2 has finished')),
    map(() => 'Process 2 has finished')
    )

    const doSthg3 = pipe(
    tap(() => console.log('Process 3 has finished')),
    map(() => 'Process 3 has finished')
    )

    forkJoin(doSthg1(process1$), doSthg2(process2$), doSthg3(process3$)).subscribe(() => {
    console.log('Now I am complete');
    });


    Demo with forkJoin



    This works as long as your processes are not chained, i.e the input of one does not depend on the output of another.



    why isn't my code working ?



    Because you don't actually subscribe to forkJoin.
    Solution : for example, you can use concatMap to transform this._authService.openCorsConnection() into another Observable :



    getInitialData(){
    this._authService.openCorsConnection().pipe(
    concatMap(() => forkJoin(this._authService.x(),
    this._tService.getSystemDate(),
    this._tService.getTemp(),
    this._tService.getSettings()
    )),
    catchError(err => {
    console.log('gor error', err);
    if (err.status == 401) {
    return EMPTY;
    } else {
    return throwError(err);
    }
    }),
    ).subscribe(() => processData());
    }


    zip



    You could use zip instead of forkJoin if:




    1. all processes emit only once, then complete : for example http Get or Post requests.

    2. you want to get join outputs from your sources.


    implementation:



    zip(doSthg1(process1$), doSthg2(process2$), doSthg3(process3$))
    .subscribe(
    ([x,y,z]) => {
    console.log(`x=${x}, y=${y}, z=${z}`);
    });


    Demo with zip







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 2 '18 at 13:05

























    answered Nov 2 '18 at 11:27









    madjaouemadjaoue

    2,3561520




    2,3561520













    • @madjaous Thanks.. i will try this... Also i have updated the service body in my question. can you pls tell if any modification is required ?

      – programoholic
      Nov 2 '18 at 11:36











    • yes i need to process data for each service . I am not sure "do all your services emit once" means but yes.. all service returns data for sure.

      – programoholic
      Nov 2 '18 at 11:52











    • Thanks buddy.. Will let you know once i implement.

      – programoholic
      Nov 3 '18 at 16:35






    • 1





      It works perfectly .....

      – programoholic
      Nov 6 '18 at 9:43



















    • @madjaous Thanks.. i will try this... Also i have updated the service body in my question. can you pls tell if any modification is required ?

      – programoholic
      Nov 2 '18 at 11:36











    • yes i need to process data for each service . I am not sure "do all your services emit once" means but yes.. all service returns data for sure.

      – programoholic
      Nov 2 '18 at 11:52











    • Thanks buddy.. Will let you know once i implement.

      – programoholic
      Nov 3 '18 at 16:35






    • 1





      It works perfectly .....

      – programoholic
      Nov 6 '18 at 9:43

















    @madjaous Thanks.. i will try this... Also i have updated the service body in my question. can you pls tell if any modification is required ?

    – programoholic
    Nov 2 '18 at 11:36





    @madjaous Thanks.. i will try this... Also i have updated the service body in my question. can you pls tell if any modification is required ?

    – programoholic
    Nov 2 '18 at 11:36













    yes i need to process data for each service . I am not sure "do all your services emit once" means but yes.. all service returns data for sure.

    – programoholic
    Nov 2 '18 at 11:52





    yes i need to process data for each service . I am not sure "do all your services emit once" means but yes.. all service returns data for sure.

    – programoholic
    Nov 2 '18 at 11:52













    Thanks buddy.. Will let you know once i implement.

    – programoholic
    Nov 3 '18 at 16:35





    Thanks buddy.. Will let you know once i implement.

    – programoholic
    Nov 3 '18 at 16:35




    1




    1





    It works perfectly .....

    – programoholic
    Nov 6 '18 at 9:43





    It works perfectly .....

    – programoholic
    Nov 6 '18 at 9:43













    0














    I have just do few days ago after lot's of search.



    The main thing is how you call list of API.



    If you call API from component.ts then you got data in that. The twist is when you call API by service the you have to store the reference of API call.



    I have done this by this way...



    var pendingAPIList : any = ;


    you can add API list in array with ref of observable.



    return new Observable(observer => {
    var obj = {
    url:url,
    param:param,
    ref : observer // <-- Hear is the main trick
    }
    this.pendingAPIList.push(obj); // Add multiple API in array
    })


    When all API added then call then...



    Observable.forkJoin(this.pendingAPIList).subscribe(response){

    // You will get data in array
    // Now return all API res in their subscribers at .ts file...

    for(let i = 0 ; i < this.pendingAPIList.lengh ; i++ ){
    this.pendingAPIList[i].ref.next(response[i]);
    this.pendingAPIList[i].ref.complete();
    }
    }


    This is working fine for me... :)






    share|improve this answer




























      0














      I have just do few days ago after lot's of search.



      The main thing is how you call list of API.



      If you call API from component.ts then you got data in that. The twist is when you call API by service the you have to store the reference of API call.



      I have done this by this way...



      var pendingAPIList : any = ;


      you can add API list in array with ref of observable.



      return new Observable(observer => {
      var obj = {
      url:url,
      param:param,
      ref : observer // <-- Hear is the main trick
      }
      this.pendingAPIList.push(obj); // Add multiple API in array
      })


      When all API added then call then...



      Observable.forkJoin(this.pendingAPIList).subscribe(response){

      // You will get data in array
      // Now return all API res in their subscribers at .ts file...

      for(let i = 0 ; i < this.pendingAPIList.lengh ; i++ ){
      this.pendingAPIList[i].ref.next(response[i]);
      this.pendingAPIList[i].ref.complete();
      }
      }


      This is working fine for me... :)






      share|improve this answer


























        0












        0








        0







        I have just do few days ago after lot's of search.



        The main thing is how you call list of API.



        If you call API from component.ts then you got data in that. The twist is when you call API by service the you have to store the reference of API call.



        I have done this by this way...



        var pendingAPIList : any = ;


        you can add API list in array with ref of observable.



        return new Observable(observer => {
        var obj = {
        url:url,
        param:param,
        ref : observer // <-- Hear is the main trick
        }
        this.pendingAPIList.push(obj); // Add multiple API in array
        })


        When all API added then call then...



        Observable.forkJoin(this.pendingAPIList).subscribe(response){

        // You will get data in array
        // Now return all API res in their subscribers at .ts file...

        for(let i = 0 ; i < this.pendingAPIList.lengh ; i++ ){
        this.pendingAPIList[i].ref.next(response[i]);
        this.pendingAPIList[i].ref.complete();
        }
        }


        This is working fine for me... :)






        share|improve this answer













        I have just do few days ago after lot's of search.



        The main thing is how you call list of API.



        If you call API from component.ts then you got data in that. The twist is when you call API by service the you have to store the reference of API call.



        I have done this by this way...



        var pendingAPIList : any = ;


        you can add API list in array with ref of observable.



        return new Observable(observer => {
        var obj = {
        url:url,
        param:param,
        ref : observer // <-- Hear is the main trick
        }
        this.pendingAPIList.push(obj); // Add multiple API in array
        })


        When all API added then call then...



        Observable.forkJoin(this.pendingAPIList).subscribe(response){

        // You will get data in array
        // Now return all API res in their subscribers at .ts file...

        for(let i = 0 ; i < this.pendingAPIList.lengh ; i++ ){
        this.pendingAPIList[i].ref.next(response[i]);
        this.pendingAPIList[i].ref.complete();
        }
        }


        This is working fine for me... :)







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 2 '18 at 11:50









        Sachin ShahSachin Shah

        1,7201515




        1,7201515






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53115864%2fangular-6-how-to-make-a-set-of-service-calls-in-parallel-and-process-data-once%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Costa Masnaga

            Fotorealismo

            Sidney Franklin