簡體   English   中英

如何在ngOnInit中使用訂閱等待API調用完成?

[英]How to wait for an API call using subscribe to finish in ngOnInit?

實際日志順序:('ngOnInit開始')('我之后aaya',this.policydetails)('Here',Object.keys(this.policy).length)

預期的日志順序:('ngOnInit start')('Here',Object.keys(this.policy).length)('after me aaya',this.policydetails)

下面的Component.ts文件片段:

ngOnInit() {
    console.log('ngOnInit started');
    this.route.params.subscribe(params => {
      this.getPoliciesService.getPolicyDetails(params.policyNo)
      .subscribe((data: PoliciesResponse) => {
        this.policy = data.data[0];
        this.flattenPolicy();
        console.log('Here', Object.keys(this.policy).length);
    });
    });

    this.makePolicyTable();

  }

  ngAfterViewInit() {
    console.log('after me aaya', this.policydetails);
    const table = this.policydetails.nativeElement;
    table.innerHTML = '';
    console.log(table);
    console.log(this.table);
    table.appendChild(this.table);
    console.log(table);
  }

下面的Service.ts文件片段:

getPolicyDetails(policyNo) {
  const serviceURL = 'http://localhost:7001/getPolicyDetails';
  console.log('getPolicyDetails service called, policyNo:', policyNo);
  const params = new HttpParams()
    .set('policyNo', policyNo);
  console.log(params);
  return this.http.get<PoliciesResponse>(serviceURL, {params} );
}

與以下API調用相對應的JS文件片段:

router.get('/getPolicyDetails', async function(req, res) {
    let policyNo = (req.param.policyNo) || req.query.policyNo;
    console.log('policyNo', typeof policyNo);
    await helper.getPolicyDetails({'policyNo' : policyNo}, 
        function(err, data) {
            console.log(err, data)
            if (err) {
                return res.send({status : false, msg : data});
            }
            return res.send({status : true, data : data});
    });
});

誰能建議我在什么地方需要異步等待預期的日志順序?

如果你想this.makePolicyTable()被調用的Web請求(僅后getPolicyDetails )完成,那么你應該把里面的那個呼叫.subscribe()塊:

ngOnInit() {
  console.log('ngOnInit started');
  this.route.params.subscribe(params => {
    this.getPoliciesService.getPolicyDetails(params.policyNo)
      .subscribe((data: PoliciesResponse) => {
        this.policy = data.data[0];
        this.flattenPolicy();
        console.log('Here', Object.keys(this.policy).length);

        this.makePolicyTable();
      });
  });
}

您可能還需要將ngAfterViewInit()的表邏輯也移到subscribe()塊內。

基本上,任何需要等待異步調用完成的邏輯都應在.subscribe()塊內觸發。 否則,如您所見,它可以在Web請求恢復之前運行。

最后,我將此Web服務調用移至ngAfterViewInit()而不是ngOnInit() 然后,您可以確保在Web服務調用完成時,已全部設置了Angular組件和視圖以供您操作。

您還可以在組件中將標志變量設置為false,然后在異步調用完成時將其設置為true,並使用* ngIf語法基於該標志變量呈現HTML。

暫無
暫無

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

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