Home > Software design >  Angular Typescript - Async await on internal subscription
Angular Typescript - Async await on internal subscription

Time:11-03

I have a function like this;

openModalWhenRemoveItem() {
  callRemoveService();
  openMyModal();
}

callRemoveService() function has a subscribe and it's async function, the openMyModal() function must be invoked after callRemoteService()

callRemoveService() {
  combineLatest(myAccountSelector$, myCompanySelector$).pipe(
    switchMap(res) => 
    this.myService.remove(res[0].id, res[1].id))
    .subscribe((res)=> console.log(res))
}

I need to create a function that has to wait the internal subscription in callRemoveService() before calling the openModal(). I want to try with async await but I can't find a solution. I tried in this way:

async callRemoveService() {
  await combineLatest(myAccountSelector$, myCompanySelector$).pipe(
    switchMap(res) => 
    this.myService.remove(res[0].id, res[1].id))
    .subscribe((res)=> console.log(res))
}

openModalWhenRemoveItem() {
  callRemoveService().then(() => {openMyModal();});
  
}

but it doesn't work. I cant put openMyModal() function into subscribe.

CodePudding user response:

The solution in your case would be to return the Observable from the callRemoveService method instead of subscribing to it. The caveat with this approach is that you need to call subscribe in all the places where you call callRemoveService.

If you do that, then it is trivial:

callRemoveService(): Observable<any> {
  return combineLatest(myAccountSelector$, myCompanySelector$).pipe(
    switchMap(res) => 
    this.myService.remove(res[0].id, res[1].id));
}

Then your openModalWhenRemoveItem method becomes this:

openModalWhenRemoveItem() {
  callRemoveService().subscribe(() => {
    openMyModal();
  };
}

CodePudding user response:

combineLatest is a RxJS operator, it returns an Observable. You can't simply await an Observable, it's not a Promise. Simply subscribe to it.

callRemoveService(): Observable<any> {
  return combineLatest(myAccountSelector$, myCompanySelector$);
}

and then :

openModalWhenRemoveItem() {
  callRemoveService().subscribe(openMyModal);
}

Alternatively, you can transform your Observable to Promise using the lastValueFrom operator, and await it :

callRemoveService(): Promise<any> {
  return lastValueFrom( combineLatest(myAccountSelector$, myCompanySelector$)) ;
}

async openModalWhenRemoveItem() {
  await callRemoveService();
  openMyModal();
}
  • Related