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

Vir*_*sad 5 node.js typescript angular angular6

实际日志顺序:('ngOnInit开始') ('在我之后aaya', this.policydetails) ('这里', Object.keys(this.policy).length)

预期的日志顺序:('ngOnInit开始') ('这里', Object.keys(this.policy).length) ('在我之后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);
  }
Run Code Online (Sandbox Code Playgroud)

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} );
}
Run Code Online (Sandbox Code Playgroud)

与以下 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});
    });
});
Run Code Online (Sandbox Code Playgroud)

谁能建议我到底需要在哪里异步等待预期的日志顺序?

Mat*_*ard 5

如果您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();
      });
  });
}
Run Code Online (Sandbox Code Playgroud)

您可能还想移动块ngAfterViewInit()内的表逻辑subscribe()

基本上,任何需要等待异步调用完成的逻辑都应该在.subscribe()块内触发。否则,正如您所看到的,它可以在网络请求返回之前运行。

最后,我会将此 Web 服务调用移至ngAfterViewInit()而不是ngOnInit(). 然后,您可以确保 Angular 组件和视图都已设置好,以便您在 Web 服务调用完成时操作它们。