繁体   English   中英

Angular 2构造函数ngOnInit未定义属性TypeScript

[英]Angular 2 Constructor ngOnInit undefined property TypeScript

我正在尝试从(Firebase)数据存储返回的数据初始化对象的值。 我可以看到返回的数据,但无法将其分配给局部变量。 我正在自学TypeScript,Angular 2和Firebase,所以这可能是一个“ duh”问题...

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"
   }
 }
}

任何帮助表示赞赏! 谢谢!

这是因为this并不引用组件本身。 绑定函数或使用fat arrow =>函数:

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

要么

...getUserProfile().on('value', snap => {
  // this is properly bound here
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM