我正在尝试将JSON响应中的值设置为一些变量。但是未设置该值,并试图在Console.log()中查看这些值时返回“ undefined”。
有人知道我在做什么错吗?
public data: any;
carbs: string;
fat:any;
protein:any;
constructor(public navCtrl: NavController,public userprovider: UserProvider) {
//returns json array
this.user = this.userprovider.getUser(userid);
this.user.toPromise().then(res => {
this.carbs = res[0].carbs;
this.fat = res[0].fat;
this.protein = res[0].protein;
});
console.log(this.carbs);
//pass the data here
this.data = {"Macros":[{"Macros":"Prot","time":this.protein,"color":"#3fa9f5","hover":"#57c0f5"},{"Macros":"Carb","time":this.carbs,"color":"rgb(236, 240, 241)","hover":"rgb(236, 240, 241)"},{"Macros":"Fat","time":this.fat,"color":"rgb(52, 73, 94)","hover":"rgb(52, 73, 94)"}]};
}
答案 0 :(得分:1)
这是因为console.log(this.carbs);
是在this.carbs = res[0].carbs;
完成之前启动的。因此,不要在范围内调用函数,而应在范围内调用它。
从以下位置调用函数:
this.user.toPromise().then(res => {
this.carbs = res[0].carbs;
this.fat = res[0].fat;
this.protein = res[0].protein;
this.yourFunction(res[0].protein, res[0].carbs, res[0].fat );
});
。 。
yourFunction(protein, carbs, fat){
this.data = {"Macros":[{"Macros":"Prot","time":protein,"color":"#3fa9f5","hover":"#57c0f5"},{"Macros":"Carb","time":carbs,"color":"rgb(236, 240, 241)","hover":"rgb(236, 240, 241)"},{"Macros":"Fat","time":fat,"color":"rgb(52, 73, 94)","hover":"rgb(52, 73, 94)"}]};
}