【问题标题】:Ionic 2: Get index of each item in list and store it into FirebaseIonic 2:获取列表中每个项目的索引并将其存储到 Firebase
【发布时间】:2017-01-13 02:49:47
【问题描述】:

我目前正在开发 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});

     }
     }

【问题讨论】:

    标签: firebase firebase-realtime-database ionic2 angularfire2


    【解决方案1】:

    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 返回一个承诺。

    【讨论】:

    • 感谢您的帮助!显然它确实更新了 Firebase 中的优先级。但是,我发现它只工作了一半。有时当我重新排列项目时,它会恢复到第一个顺序。
    • 在更新完成之前重新排序可能会变得很奇怪。 update 返回一个承诺;在解决之前你不应该重新排序,但 Ionic 是否让你强制执行这是另一回事。
    • 好的!添加编辑/完成按钮可能有效吗?它只会在我点击完成按钮后更新。
    猜你喜欢
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2019-08-11
    相关资源
    最近更新 更多