Issue
After fetching value from DB, I am trying to put it in a variable, but when I do that it gives me error:
core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined
TypeError: Cannot set property 'userNm' of undefined
Here is my ts
code:
userNm: string ='';
ngOnInit(){
console.log("trying...");
firebase.firestore().collection(`Students`)
.where("authId", "==", this.userId)
.get()
.then(querySnapshot => {
querySnapshot.forEach(function(doc) {
console.log(doc.data().Name); // OK RESULT IN CONSOLE.LOG,NAME IS String in db.
this.userNm=doc.data().Name; // ERROR HERE
console.log(this.userNm)
console.log(doc.id, " ===> ", doc.data());
});
});
Screenshot of console and database:
Solution
this
keyword in a Javascript function()
refers to the scope of the function. To use member variables, use arrow function construct. You could try the following
firebase.firestore().collection(`Students`)
.where("authId", "==", this.userId)
.get()
.then(querySnapshot => {
querySnapshot.forEach((doc) => { // <-- Use arrow function here
console.log(doc.data().Name);
this.userNm = doc.data().Name;
console.log(this.userNm)
console.log(doc.id, " ===> ", doc.data());
});
});
Answered By - ruth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.