我正在尝试将promise中的值分配给变量(property)。我可以从console.log中检索值。但是,当我试图将它分配给“这个”时,它将无法工作。看下面的代码:
export class AppComponent implements OnInit {
graphData:any;
constructor(public _RelaticsService:RelaticsService, public _RelaticsDataTransformService:RelaticsDataTransformService) {
}
ngOnInit() {
this._RelaticsService.GetData('persons', '37035202-abf8-4822-b8a5-b492c97a4c83', '123456')
.then((val) =>
this._RelaticsDataTransformService.ObjectTreeTransformation(val)
)
.then((val) => {
console.log(val); // logs object
this.graphData = val; // assigns object to this.graphdata
console.log(this.graphData); // logs object
})
.catch((err) => console.log("rejected:", err));
console.log(this.graphData) // logs undefined??
}
}
答案 0 :(得分:4)
console.log(this.graphData) // logs undefined??
在
之前执行this._RelaticsService.GetData('persons', '37035202-abf8-4822-b8a5-b492c97a4c83', '123456')
.then((val) =>
this._RelaticsDataTransformService.ObjectTreeTransformation(val)
)
.then((val) => {
console.log(val); // logs object
this.graphData = val; // assigns object to this.graphdata
console.log(this.graphData); // logs object
})
.catch((err) => console.log("rejected:", err));
这个
this._RelaticsDataTransformService.ObjectTreeTransformation(val)
)
.then( /* passed code */ )
只计划传递的代码以便以后执行(当调用返回时)并继续执行以下语句。
因此,您的代码似乎工作正常,只是检查无效。