简体   繁体   中英

Angular waiting bar for all async operation in ngOnInit

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;
    }
    );
  }

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;
    }
));

}

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