【发布时间】:2018-08-13 22:09:26
【问题描述】:
我试图将 JSON 响应中的值设置为一些变量。但该值未设置并在尝试查看 Console.log() 中的值时返回“未定义”。
有谁知道我在这里做错了什么?
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)"}]};
}
【问题讨论】:
-
你确定 this.user 不是未定义的吗?
-
这个用户返回json,res=>里面的console.log(res[0].carbs)也输出正确的值。
-
ionViewDidLoad() {} 使用这个函数。复制粘贴你的代码并检查会发生什么。
-
那里也未定义。
-
原因很可能是在此之前.carbs = res[0].carbs;行 console.log(this.carbs);已启动。
标签: angular typescript ionic-framework