簡體   English   中英

如何等待 http 請求以 angular 8 完成?

[英]how can I wait the http request to finish in angular 8?

這是我的服務

existWayBillByRsBillNumber(billNumber: string){
    return  this.http.get<boolean>(this.baseUrl + 'Common/ExistWayBillByRsBillNumber/'+billNumber);
  }

這是服務電話

this.commonService.existWayBillByRsBillNumber(this.buyerWaybill.waybillNumber).subscribe(
  response => {
    let exist = <Boolean>response;
    if (exist) {
      console.log(1);
      this.toastService.error('ზედდებული ნომრით ' + this.buyerWaybill.waybillNumber + " უკვე არსებობს!");
      return false;
    }
  }
);
console.log(2);
    }
  }
);

在控制台中打印 2 和 1 之后在此處輸入圖像描述

我如何等待服務響應

您的代碼按預期工作。

如果我們要逐步執行您的代碼,它會是這樣的:

  1. 呼叫服務
  2. 發出http請求
  3. 等待響應,返回 observable
  4. 控制台日志(2)
  5. ...
  6. 返回 HTTP 響應
  7. 執行訂閱者的回調
  8. console.log(1) [if 條件內]

所以事實是,您已經在等待您的服務響應——這是您檢查響應並有條件地將 1 記錄到控制台的地方。

您在如何提出請求和處理響應方面存在一些問題,但您的問題有效地詢問了為什么 2 在 1 之前被記錄。

編輯:

從組件的角度來看,這是上述步驟的物理版本:


console.log('1. Call service);

this.commonService
  .existWayBillByRsBillNumber(this.buyerWaybill.waybillNumber)
  .subscribe(response => {
    console.log('7. Execute callback of subscriber'); 

    if (response === true) {
      // handle true
    } else {
      // handle false
    }
  });

console.log(2);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM