Angular 使用离子框架的角度未定义变量
我试图将JSON响应中的值设置为一些变量。但该值未设置,在尝试查看Console.log()中的值时返回“undefined” 有人知道我做错了什么吗Angular 使用离子框架的角度未定义变量,angular,typescript,ionic-framework,Angular,Typescript,Ionic Framework,我试图将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
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)"}]};
}
这是因为
console.log(this.carbs)代码>在this.carbs=res[0]之前启动代码>已完成。因此,与其在范围外调用函数,不如在范围内调用它
从以下位置调用函数:
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 );
});
。
.
是否确定this.user未定义?此用户返回res=>中的json、console.log(res[0].carbs)并输出正确的值。ionViewDidLoad(){}使用此函数。复制粘贴您的代码到其中,并检查发生了什么。此处也未定义。原因很可能是在此之前。carbs=res[0]。carbs;line console.log(this.carbs);已启动。相同:错误类型错误:“this.data未定义”请前来聊天,除非stackoverflow将阻止评论
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)"}]};
}