最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何使用subscribe在ngOnInit中等待API调用?

运维笔记admin9浏览0评论

如何使用subscribe在ngOnInit中等待API调用?

如何使用subscribe在ngOnInit中等待API调用?

实际日志顺序:('ngOnInit started')('after a aaya',this.policydetails)('Here',Object.keys(this.policy).length)

预期的日志顺序:('ngOnInit started')('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});
    });
});

任何人都可以建议我在哪里需要异步 - 等待预期的日志顺序?

回答如下:

如果您希望仅在Web请求(this.makePolicyTable())完成后调用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()。然后,您可以确保Angular组件和视图都已设置为在Web服务调用完成时操作它们。

发布评论

评论列表(0)

  1. 暂无评论