0

I am to loading some main data just after user logged in and in main layout page. There is multiple API request are done for load main data. so i want to put on hold other API request until the main api request is finished

The main API requests is done in sequence manner also.

I have already added HttpInterceptor for adding some headers and all.

Explaining what happening right now.

  • i have _layout components and its have tags so all other pages will loads in this components.
  • _layout is loading some main data on ngOnInit which will use in further API requests

Issue is while refreshing the page,other API request is not waiting for to complete the requests of main API requests which started in _layout components.

we cant identify how many API requests will call after _layout components init because all routing is done in this.

Rajdip Khavad
  • 257
  • 1
  • 3
  • 9

4 Answers4

2

In your _layout component template, create an ng-container tag and put all your child component tags inside the ng-container. Now you can have an ngIf on the ng-container tag to not render the child components if main api has not given response yet. This way the child components Api will not get triggered. Hope this helps.

Manu Mathew
  • 140
  • 1
  • 8
1

I think for this you should use .flatMap() operator of rxjs. This operator is generally used to call the api's in sequential manner.

Please check the below links for more information: http://reactivex.io/documentation/operators/flatmap.html https://stackoverflow.com/a/40666072/9766269

0
this.http.get(url).subscribe(res => {
         // Main Api is Called here
        }, error => {
          console.log(error);
        }, () => {
          console.log('When api Request is Complated');
            // Rest of the API Called here When Main Api In Completed.
        }
      );
upinder kumar
  • 819
  • 6
  • 8
0

Try this:

this.http.get(mainApiUrl).pipe(
    switchMap(
        mainApiResponse => {
        // mainApiResponse has result from main api
        return forkJoin(
            [
                this.http.get(otherApiUrl1),
                this.http.get(otherApiUrl2)
            ]
        ).pipe(map(otherResponsesArr => [mainApiResponse, ...otherResponsesArr]))
    })
).subscribe(responseArr => {
        mainResponse = responseArr[0];
        otherResponse1 = responseArr[1];
        otherResponse2 = responseArr[2];
    });

Explanation

The main api is called and on getting response, we use the switchmap operator to retrieve the output of first api call, cancel the subscription and pass the result to call the next set of api using forkjoin (actual usecase may vary).

Manu Mathew
  • 140
  • 1
  • 8