我试图将返回值从服务分配给组件时遇到问题。
ngOnInit() {
this.getInspectionData();
}
getInspectionData() {
this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`)
.subscribe(data => {
console.log(`this is data returned: `, data);
}, error => {
console.log('failed to get data', error);
}, () => {
console.log('getInspectionResult successfully processed');
});
}
它成功地在console.log中获得了返回值
在subscribe()
内。似乎没有问题。甚至我将console.log设置为subscribe()
中的变量:
.subscribe(data => {
this.inspectionResult = data;
console.log(`value from getInspectionData: `, this.inspectionResult);
它正确地给了this.inspectionResult
输出。
它应该是正确的,对吗?然后我添加this.inspectionResult = data;
但....
当我测试它时,变量出错,它得到'{}'
。代码如下:
ngOnInit() {
this.getInspectionData();
console.log(`value from getInspectionData: `, this.inspectionResult);
}
getInspectionData() {
this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`)
.subscribe(data => {
this.inspectionResult = data;
}, error => {
console.log('failed to get data', error);
}, () => {
console.log('getInspectionResult successfully processed');
});
}
顺便说一句,我已经分配了这样的变量:
inspectionResult: InspectionResult = <InspectionResult>{};
inspectionResultData: InspectionResultData = <InspectionResultData>{};
我的问题是:
this.inspectionResult
中的console.log()
应该在ngOnInit()
之后运行)可能是由于
this.getInspectionData(); console.log(getInspectionData();
,this.inspectionResult);
在这种情况下,this.getInspectionData()可能会延迟此过程。但是在完成上述方法之前,console.log()已经开始了。
你必须等待方法完成。请参考,你会得到一些清晰度
value from getInspectionData: