0

I would like to add a waiting bar line this to make user to wait until all the necessary data are retrieved.
The problem is that I have several HTTP call so I don't know if exist a simple way to catch the end of all these request (I thought about a counter that I increment for each end of call at only when all the methods end I have to hide the waiting bar).
Since this is a common problem, there is a simple way to make this?
For example this is a component code:

ngOnInit() {
   this.spinner.show();
   call1();
   call2();
   call3();
   .....
   callN();

   //At the end of all method
   this.spinner.hide();
}

call1() {
    this.service.getAtti().subscribe((apiResult: ApiResult<a[]>) => {   
      this.a = apiResult.Data;
    }
    );
  }

  call2() {
    this.service.getDestinatari().subscribe((apiResult: ApiResult<b[]>) => {
      this.b =  apiResult.Data;
    }
    );
  }

  call3() {
    this.service.getRichiedenti().subscribe((apiResult: ApiResult<c[]>) => {
      this.c =  apiResult.Data;
    }
    );
  }

  callN() {
    this.service.getMessi().subscribe((apiResult: ApiResult<d[]>) => {
      this.d = apiResult.Data;
    }
    );
  }
luca
  • 3,248
  • 10
  • 66
  • 145
  • seems to be an duplicate of this https://stackoverflow.com/questions/41734921/rxjs-wait-for-all-observables-in-an-array-to-complete-or-error. You can use ``Observable.forkJoin`` to wait for all to complete and then do your work you want. – J. Knabenschuh Mar 13 '19 at 16:17
  • forkjoin doesn't work with method arguments, can you help? – luca Mar 13 '19 at 16:28

1 Answers1

-1

forkjoin doesn't work with method arguments, can you help?

Sorry, I dont understand the question.

Maybe following will answer it:

ngOnInit() {
   this.spinner.show();
   let calls = [];
   calls.push(call1());
   calls.push(call2());
   calls.push(call3());
   .....
   calls.push(callN());

   Observable.forkJoin(calls).subscribe(results => { 
     this.spinner.hide();
   });
}

call1() {
    return this.service.getAtti().pipe(tap((apiResult: ApiResult<a[]>) => {   
      this.a = apiResult.Data;
    }
    ));
  }

  call2() {
    return this.service.getDestinatari().pipe(tap((apiResult: ApiResult<b[]>) => {
      this.b =  apiResult.Data;
    }
    ));
  }

  call3() {
    return this.service.getRichiedenti().pipe(tap((apiResult: ApiResult<c[]>) => {
      this.c =  apiResult.Data;
    }
    ));
  }

  callN() {
    return this.service.getMessi().pipe(tap((apiResult: ApiResult<d[]>) => {
      this.d = apiResult.Data;
    }
));

}

J. Knabenschuh
  • 747
  • 4
  • 15
  • 1
    Knabenschuh, you needn't use spread operator in forkJoin(...calls), just forkJoin(calls). Thus, call1, call2.. must be observables, so, NOT subscribe, use (pipe(tap(result=>{....})) – Eliseo Mar 13 '19 at 16:38