Node.js 如何在ngOnInit中使用subscribe等待API调用完成?
实际日志顺序: (“恩戈尼特开始了”) ('after me aaya',这是保单详情) ('Here',Object.keys(this.policy).length) 预期日志顺序: (“恩戈尼特开始了”) ('Here',Object.keys(this.policy).length) ('after me aaya',这是保单详情) Component.ts文件片段如下: Service.ts文件片段如下:Node.js 如何在ngOnInit中使用subscribe等待API调用完成?,node.js,angular,typescript,angular6,Node.js,Angular,Typescript,Angular6,实际日志顺序: (“恩戈尼特开始了”) ('after me aaya',这是保单详情) ('Here',Object.keys(this.policy).length) 预期日志顺序: (“恩戈尼特开始了”) ('Here',Object.keys(this.policy).length) ('after me aaya',这是保单详情) Component.ts文件片段如下: Service.ts文件片段如下: getPolicyDetails(policyNo) { const se
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} );
}
有人能建议我需要在哪里异步等待预期的日志顺序吗 如果希望仅在web请求(
getPolicyDetails
)完成后调用this.makePolicyTable()
,则应将该调用放入.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服务调用完成时对其进行操作。您还可以在组件中将标志变量设置为false,然后在异步调用完成时将其设置为true,并基于该标志变量使用*ngIf语法呈现HTML。getPolicyDetails您可以仅在ngAfterViewInit内部调用。不需要2个生命周期
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});
});
});
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();
});
});
}