M Jenkins
M Jenkins

Reputation: 53

Angular 5 typescript call service within a service and combine data

I'm trying to call a service within a service and combine the data. The two services are 1) shipDateChangeService and 2) applicantService. I store the data from each service in shipClasses and applicantClasses respectively. I then want to combine the data and store it in a results array. I'm trying to determine the most efficient way to do this and since I'm new to Angular and typescript it has been going well. Below is what I currently have but I'm running into scoping problems and I don't want to create too many loops.

UPDATE I forgot to mention that data from the first call will be used to request data from the second call.

Code:

    this.result = [];
    this.shipClasses = [];
    this.applicantClasses = [];

    this.shipDateChangeService
            .getShipDateChangeClasses(query)
            .finally(() => {
                this.blockResults = false;
                this.shipClasses.forEach(function(value, key) {
                    this.push({'indSsn' : value.indSsn, 'ofcSymbId' : value.ofcSymbId, 'recstaLocCd' : value.recstaLocCd, 'rctgStnId' : value.rctgStnId, 'tngShipDt' : value.tngShipDt, 'name' : '' });
                    this.applicantService.getApplicant(value.indSsn)
                    .finally(() => {
                        console.log('within 2nd finally');
                    })
                    .subscribe(applicantList => (this.applicantClasses = applicantList));

                }, this.results);
            })
            .subscribe(classList => (this.shipClasses = classList));

Upvotes: 1

Views: 603

Answers (2)

Sachin Shah
Sachin Shah

Reputation: 4533

Please try this way

When you API calls are not dependent on another API param the you can use this.

forkJoin()

With the use of forkJoin you can call multiple API at a time and you will get response in array.

Ex.

forkJoin(API_1 , API_2)
.subscribe(([res1, res2]) => {

You can find more Here

When you have dependent res to another API then follow this.

POST('url', data).pipe(
   concatMap(result1 => secondPOSTCallToAPI('url', result1))
   concatMap( result2 => thirdPOSTCallToAPI('url', result2))
   concatMap(result3 => fourthPOSTCallToAPI('url', result3))
  ....
 ).subscribe((data) => {
    console.log(data);
 });

This is works for me.!

Upvotes: 1

Sachin Gupta
Sachin Gupta

Reputation: 5321

If the two service calls are not dependent on each other then you can have multiple parallel API calls and use forkjoin to combine all results into a single array. If the two calls are dependent, use switchMap

Upvotes: 0

Related Questions