0

Im trying to set values from a JSON response into some variables. But the value is not set and returns "undefined" when trying to see the values in Console.log().

Does anyone know what I'm doing wrong here?

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)"}]};


}
12
  • Are you sure that this.user is not undefined? Commented Aug 10, 2018 at 12:40
  • this user returns the json, console.log(res[0].carbs) inside the res => also outputs the right value. Commented Aug 10, 2018 at 12:42
  • ionViewDidLoad() {} use this function. Copy paste your code inside of it and check what happens. Commented Aug 10, 2018 at 12:43
  • Undefined there as well. Commented Aug 10, 2018 at 12:45
  • reason is highly probable that before this.carbs = res[0].carbs; line console.log(this.carbs); is initiated. Commented Aug 10, 2018 at 12:45

1 Answer 1

1

It is because that console.log(this.carbs); is initiated before this.carbs = res[0].carbs; is completed. Therefore, instead of calling your function outside the scope, call it inside of your scope.

Call your function from:

 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)"}]};
}
Sign up to request clarification or add additional context in comments.

2 Comments

The same: ERROR TypeError: "this.data is undefined"
Come to chat please, unless stackoverflow will block comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.