Home > Enterprise >  How to wait utill i get response from service?
How to wait utill i get response from service?

Time:12-27

I have this method:

 async cancelAppointment(id: string) {
    !id ||
    this.api
      .post("/cancel", { appointmentId: id})
      .subscribe((response: any) => {
        if(this.validationMessage(response)){return false;}
      });
  }

In other ts file i have this:

async cancle(){
    await this.ticketService.cancelAppointment(this.ticketService.appointment.setup.APPOINTMENT_ID);
}

What i want to achive if something like this:

if(await !this.service.cancelAppointment(this.ticketService.appointmentId)) {
//do something
}

but it not working any idea?

CodePudding user response:

In Angular, you would probably rewrite the cancelAppointment()-method something like this:

cancelAppointment(id: string): Observable<boolean> {
    // Assumption: If id is null, cancellation is impossible => therefore return false:
    if (!id) { 
        return of(false);
    }
    return this.api.post("/cancel", { appointmentId: id}).pipe(
            map((response: any) => !this.validationMessage(response))
        );
}

Then there are two possibilities to call the method above:

Option 1: using 'subscribe', as you would typically do it in Angular

cancel() {
    this.cancelAppointment(this.ticketService.appointmentId).subscribe(
        (isCancelled: boolean) => {
            if(!isCancelled) {
                //do something
            }
        }
    )
}

Option 2: using async/ await

async cancel() {
    const isCancelled = await this.cancelAppointment(this.ticketService.appointmentId);
    if(!isCancelled) {
        //do something
    }
}
  • Related