Ionic 2:获取列表中每个项目的索引并将其存储到Firebase中

时间:2017-01-13 02:49:47

标签: firebase firebase-realtime-database ionic2 angularfire2

我目前正在开发Ionic 2移动应用程序。我有一个使用AngularFire2从我的Firebase获得的项目列表。我在列表上实现了重新排序功能。我希望能够将项目的索引存储在列表中并将其发送到我的Firebase,以便我可以使用索引根据用户的首选项确定项目的优先级。有没有办法可以做到这一点?我试图将“索引”发送到我的Firebase,但它没有用。

HTML:         

      <ion-list reorder="true" (ionItemReorder)="reorderItems($event)">
        <ion-item *ngFor="let item of categories; let i = index;">
          {{i+1}}. {{item.name}}
        </ion-item>

      </ion-list>
    </ion-content>

打字稿:

     export class ManageFavouritesPage {
      fireAuth: any;
      items: any;
      categories: any;
      categorykey: any;

      constructor(public navCtrl: NavController, public af: AngularFire, private toastCtrl: ToastController, public authData: AuthData) {

        let userid = this.authData.getID();
        this.items = af.database.list(`/users/${userid}/favourites`)
          .subscribe(data => this.categories = data)  
      }


      reorderItems(indexes) {
        let element = this.categories[indexes.from];
        let element2 = this.categories[indexes.to].$key;
        this.categories.splice(indexes.from, 1);
        this.categories.splice(indexes.to, 0, element);
        let userid = this.authData.getID();
        this.items = this.af.database.object(`users/${userid}/favourites/${element2}`).update( {priority: indexes.to});

     }
     }

1 个答案:

答案 0 :(得分:0)

fromto之间所有元素的索引都会发生变化。您可以使用多地点update来一次更新所有这些内容:

reorderItems(indexes) {

  // Reorder the array:

  this.categories.splice(indexes.from, 1);
  this.categories.splice(indexes.to, 0, element);

  // Build the multi-location update:

  let min = Math.min(indexes.from, indexes.to);
  let max = Math.max(indexes.from, indexes.to);

  let reindexed = {};
  for (let i = min; i <= max; ++i) {
    reindexed[`${this.categories[i].$key}/priority`] = i;
  }

  // Update the reordered elements:

  let userid = this.authData.getID();
  this.af.database.object(`users/${userid}/favourites`).update(reindexed);
}

此外,this.items很可能不是您认为的那样,因为subscribe会返回RxJS订阅而update会返回一个承诺。