【问题标题】:Angular 2 Constructor ngOnInit undefined property TypeScriptAngular 2 构造函数 ngOnInit 未定义属性 TypeScript
【发布时间】:2018-01-14 19:59:23
【问题描述】:

我正在尝试从 (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"
   }
 }
}

感谢任何帮助! 谢谢!

【问题讨论】:

标签: javascript angular typescript firebase


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢!我是 JavaScript / Type Script 的新手,这让我发疯了......不是这两种语言的粉丝......
  • 好吧,耐心点,你会得到它并享受它。
  • 我最终可能会得到它,我不确定我是否会喜欢它...... :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 2016-09-22
  • 1970-01-01
  • 2016-11-07
  • 2017-06-26
  • 2021-06-19
  • 2021-12-17
相关资源
最近更新 更多