When attempting to retrieve a value from the database and store it in a variable, an error is encountered:
core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined
TypeError: Cannot set property 'userNm' of undefined
Below is the code snippet in TypeScript (ts
):
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 showing the error and database records: