【问题标题】:AngularFire - Push data from firestore collection query into an arrayAngularFire - 将来自 firestore 集合查询的数据推送到数组中
【发布时间】:2019-05-12 07:34:51
【问题描述】:

我正在查询 Firestore 集合并成功检索结果。但是,我正在使用一个可排序的角度插件,它需要一个数组来排序。

我遇到的问题是项目被推入数组,但是当新项目进入时我找不到正确的位置来清除数组。如果不清除数组,返回的结果开始在数组中重复。

是否有人可以帮助重构下面的代码,以便我可以成功地将集合结果推送到数组中并在正确的位置清除它?

...
itemsArray = []
...

getData(){
    this.issueCollection = this.afs.collection<any>(`users/${user}/projects/${project}/issues`, ref => {
      return ref.orderBy('order');
    });
    this.issues = this.issueCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;

        this.itemsArray.push({ id, ...data });

        return { id, ...data };
      }))
    );
  }

HTML - 我如何需要 HTML 来显示结果

<ul>
   <li *ngFor="let issue of itemsArr">
      {{ issue.issueName }}
   </li>
</ul>

更新 - 这似乎有效

  getData(){
    this.issueCollection = this.afs.collection<any[]>(`users/${user}/projects/${project}/issues`, ref => {
      return ref.orderBy('issue_order');
    });
    this.issues = this.issueCollection.snapshotChanges().pipe(
      map(actions => {
      this.itemsArr = [];
      return actions.map(a => {

        const data = a.payload.doc.data();
        const id = a.payload.doc.id;


        this.itemsArr.push({ id, ...data });


        return { id, ...data };
      });
    }))
  }

【问题讨论】:

    标签: angular google-cloud-firestore angularfire5


    【解决方案1】:

    我要做的是让它订阅该集合并执行此操作:

    getData(){
        this.issueCollection = this.afs.collection<any[]>(`users/${user}/projects/${project}/issues`, ref => {
          return ref.orderBy('order');
        });
        this.issues = this.issueCollection.snapshotChanges().pipe(
          map(actions => actions.map(a => {
                const data = a.payload.doc.data();
                const id = a.payload.doc.id;
    
                return { id, ...data };
            }))).subscribe((items: any[]) => {
              this.itemsArray = [];
              this.itemsArray = items;
           });
      }
    

    这将允许您清空 itemsArray 并重新填充它。而不是只推送数组而不是清空它。

    【讨论】:

    • 感谢@Swoox 的快速响应! - 我已经复制了您的答案,但出现了一些错误。在第二个“.map”上,我得到“类型'{}'上不存在属性'map'”。第二个错误出现在“.subscribe”上——“OperatorFunction”类型上不存在属性“subscribe”。
    • 感谢 Swoox。不幸的是,完全相同的错误。就在第二张地图上并订阅。如果我从订阅中删除代码,地图错误就会消失。 “'{}' 类型上不存在属性 'map'”和“'OperatorFunction' 类型上不存在属性 'subscribe'。”
    • 这是由this.afs.collection&lt;any&gt; 正确引起的,使其this.afs.collection&lt;any[]&gt;subscribe((items: any) =&gt; { 应该修复它。
    • 仍然没有运气......对于可能导致这些错误的原因有点困惑。如果有帮助,我正在使用 AngularFire 5
    • 使用 rxjs 5 还是 6?如果使用 6,请使用 import { map } from 'rxjs/operators';
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2018-09-23
    • 2018-06-19
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多