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!
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
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.