0
votes

I have an Ionic2 app using firebase as the backend. In the Ionic app I have a product page, when I add a new product in the control panel and push it to firebase, If I am viewing the product page in the ionic app, the new product is added, but all items in the list are duplicated also.

If I were to add a new item when a user is currently viewing the product list, they will see the whole list duplicating, but if you leave that screen and visit it again, the list is back to normal with one of each item.

This is the code I am using in my ionic app to pull the products through from firebase.

  public menuItems: Array<any> = [];
  public selectedItems: Array<any> = [];
  menuItem: FirebaseListObservable<any>;

this.id = this.navParams.get('id');
      this.menuItem = af.database.list('/menuItems', {
        query: {
          orderByChild: 'category',
          equalTo: this.id
        }
      })

      this.menuItem.subscribe((data) => {
        this.menuItems = data;

        for (var i = 0; i <= this.menuItems.length - 1; i++) {
          if (this.menuItems[i].category == this.id) {
            this.selectedItems.push(this.menuItems[i]);
            this.items = this.selectedItems;
          }
        }
      })

An example:

If I have list of items like so:

  • item1
  • item2
  • item3

When I add a new item from the dashboard, and push to firebase, the ionic app will now show the following:

  • item1
  • item2
  • item3
  • item4
  • item1
  • item2
  • item3
  • item4

I am not sure why it is doing this, any help would be really appreciated.

1

1 Answers

1
votes

Quite simple. you have to do a little tweaking.

Change this:

    for (var i = 0; i <= this.menuItems.length - 1; i++) {
      if (this.menuItems[i].category == this.id) {
        this.selectedItems.push(this.menuItems[i]);
        this.items = this.selectedItems;
      }
    }

Into:

        let selectedItems: any[] = [];
        for (var i = 0; i <= this.menuItems.length - 1; i++) {
          if (this.menuItems[i].category == this.id) {
            selectedItems.push(this.menuItems[i]);
          }
        }
        this.items = selectedItems;