0

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.

Andreas
  • 21,535
  • 7
  • 47
  • 56
DBr8
  • 3
  • 2
  • Which is the variable/property that is not accessible? – Nitheesh Apr 09 '18 at 14:48
  • What is `this.afs` and/or `this.afs.collection`? – Andreas Apr 09 '18 at 14:49
  • This is not a scope problem, it's an async problem. Your else block does not synchronously set itemsFirebaseRef – Nicholas Tower Apr 09 '18 at 14:49
  • thanks for all you help. Nicholas and Durga are right, it is a asynchronous response issue. I may have to re-structure my code to make it work. Not sure how to do that yet but will look for answers from Durga's link. – DBr8 Apr 10 '18 at 03:00

1 Answers1

0

Your problem is that in the else part the assignment to itemsFirebaseRef is inside the callback function .subcribe(...)

That callback function will not be triggered immediately: it is called asynchronously, so when you try to access it outside the else it will still be undefined.

Duncan
  • 92,073
  • 11
  • 122
  • 156