I have a method that uses a if-else clause to decide how to setup a variable/property to load items depending on a selected CategoryName. Then i will use the variable/property OUTSIDE of the if-else clause. But i found the variable/property to be UNDEFINED OUTSIDE of the IF-ELSE clause. ie i am getting
TypeError: Cannot read property 'snapshotChanges' of undefined
It seems like it is scope blocked within the if-else clause. I have tried using let or var or this.(ie globally) to initialise the variable/property, but nothing seems to work. Here's my code:
loaditems() {
this.category = this.navParams.get('category');
var itemsFirebaseRef;
if (this.category == 'all') {
this.categoryName = 'all items';
itemsFirebaseRef = this.afs.collection('/items');
//itemsFirebaseRef is the var that i want to set and use outside of IF-ELSE
} else {
this.categoryNameRef = this.afs.doc<ItemCategory>('/categories/' + this.category);
this.categoryNameRef.valueChanges().subscribe(icat => {
this.categoryName = icat.name;
itemsFirebaseRef = this.afs.collection('/items',
ref => ref.where('category', '==', this.categoryName)
);
//itemsFirebaseRef is the var that i want to set and use outside of IF-ELSE
});
} //end IF-ELSE
this.itemsFirebase = itemsFirebaseRef.snapshotChanges().map(actions => {
//But itemsFirebaseRef will be UNDEFINED here, outside of the IF-ELSE
return actions.map(i => {
const data = i.payload.doc.data() as Item;
const id = i.payload.doc.id;
return {
id, ...data
};
});
});
etc.
} //end loaditems()
Please help.