【问题标题】:Undefined variable in angular using IONIC framework使用IONIC框架的角度未定义变量
【发布时间】: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


【解决方案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)"}]};
}

【讨论】:

  • 同理:ERROR TypeError: "this.data is undefined"
  • 请来聊天,除非stackoverflow会阻塞cmets
猜你喜欢
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 2018-10-25
  • 2014-10-15
  • 1970-01-01
相关资源
最近更新 更多