0

I am trying to initialize an object's value from data returned from a (Firebase) data store. I can see the data being returned, but i cannot assign it to a local variable. I am teaching myself TypeScript, Angular 2 and Firebase, so this might be a 'duh' question...

import ProfileProvider from ../providers/profile

@Component({...})
class Profile {
userProfile:any

constructor (public profileProvider: ProfilePRovider) {}

ngOnInit() {
  this.profileProvider.getUSerProfile().on ("value", function(snap) { 
    console.log(snap.val()); // this works, prints all my data correctly
    this.userProfile = snap.val(); // this fails, "cannot set property userProfile of undefined"
   }
 }
}

Any help is appreciated! Thanks!

1

1 Answer 1

3

This is because this does not refer the component itself. Either bind the function or use fat arrow => function:

...getUserProfile().on('value', function(snap){
  }.bind(this))

or

...getUserProfile().on('value', snap => {
  // this is properly bound here
  });
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I'm new to JavaScript / Type Script, this was driving me crazy... Not a fan of either language...
Well, be patient, you'll get it and enjoy it.
I may eventually get it, I'm not sure I'll enjoy it... :)

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.