2017-08-07 69 views
0

我想從(Firebase)數據存儲返回的數據初始化對象的值。我可以看到正在返回的數據,但我無法將其分配給本地變量。我自學打字稿,角2和火力地堡,所以這可能是一個「杜」的問題...Angular 2構造函數ngOnInit未定義的屬性TypeScript

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

任何幫助表示讚賞! 謝謝!

+0

這也是[?如何正確地做angular2打字稿一個「綁定」(https://stackoverflow.com/a/ 45136760/2545680) –

回答

3

這是因爲this不引用組件本身。無論綁定功能或使用fat arrow =>功能:

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

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

謝謝!我是JavaScript/Type Script的新手,這讓我瘋狂......不是任何一種語言的粉絲...... – banncee

+0

好吧,耐心等待,你會得到它並享受它。 – Meir

+0

我可能最終得到它,我不知道我會喜歡它...... :) – banncee