Home > Net >  Angular Message Gets Triggered Before Service Call is Done
Angular Message Gets Triggered Before Service Call is Done

Time:04-15

In my app, I have a button that enables users to calculate some data when it's clicked. To do the calculation, a service from the back-end is called. After the service finishes the calculation, I display a message that says 'Done'. But the message appears way before the service finishes calculation. Here's my code, how can I fix this?

 sendCalculateMaterialPlanDetail() {

    this.confirmDialogRef = this._dialog.open(FuseConfirmDialogComponent, {
      disableClose: false,
    });

    this.confirmDialogRef.componentInstance.confirmMessage =
      "Will start to calculate.";

    this.confirmDialogRef.afterClosed().subscribe((result) => {
      if (result) {
        this._productionService
          .sendCalculateMaterialPlanDetail(this.materialPlan)
          .subscribe((response: IMaterialPlan) => {
            this.materialPlan = response;
          });
      }
      this._messages.Show(
        "DONE",
        "DONE",
        3
      );
    });
  }

CodePudding user response:

sendCalculateMaterialPlanDetail() {

    this.confirmDialogRef = this._dialog.open(FuseConfirmDialogComponent, {
      disableClose: false,
    });

    this.confirmDialogRef.componentInstance.confirmMessage =
      "Will start to calculate.";

    this.confirmDialogRef.afterClosed().subscribe((result) => {
      if (result) {
        this._productionService
          .sendCalculateMaterialPlanDetail(this.materialPlan)
          .subscribe((response: IMaterialPlan) => {
            this.materialPlan = response;
            this._messages.Show(
            "DONE",
            "DONE",
            3
            );
          });
      }
      
    });
  }

show the text inside the inner subscribe(service result handler)

CodePudding user response:

You can use the key words await and async

sendCalculateMaterialPlanDetail() {

    this.confirmDialogRef = this._dialog.open(FuseConfirmDialogComponent, {
      disableClose: false,
    });

    this.confirmDialogRef.componentInstance.confirmMessage =
      "Will start to calculate.";

    this.confirmDialogRef.afterClosed().subscribe((result) => {
      if (result) {
      /////////////////////////////////////////////////here
        await  this._productionService
          .sendCalculateMaterialPlanDetail(this.materialPlan)
          .subscribe((response: IMaterialPlan) => {
            this.materialPlan = response;
          });
      }
      this._messages.Show(
        "DONE",
        "DONE",
        3
      );
    });
  }
  • Related