【问题标题】:How to sort data fetching from cloud firestore如何对从云 Firestore 获取的数据进行排序
【发布时间】:2019-10-09 08:03:25
【问题描述】:

我正在使用一项服务从我的 firestore 集合中获取数据,现在我要做的是按“日期”字段之一对文档进行排序 下面附上代码:

BARCODE.SERVICE.TS

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { Barcode } from '../models/barcode';
@Injectable({
  providedIn: 'root'
})
export class BarcodeService {
  barcodesCollection: AngularFirestoreCollection<Barcode>;
  barcodes: Observable<Barcode[]>;
  constructor(public afs: AngularFirestore) { 
    this.barcodesCollection = this.afs.collection('barcodes');

    this.barcodes = this.barcodesCollection.valueChanges();
  }
  getBarcodes(){
    this.barcodes = this.afs.collection('barcodes').valueChanges();
    return this.barcodes;
  }

  addBarcode(barcode: Barcode) {
    this.barcodesCollection.add(barcode);
  }
}

COMPONENT.TS(只显示需要的部分)

ngOnInit() {
    this.barcodeService.getBarcodes().subscribe(barcodes => {
      this.barcodes = barcodes;
    });
  }

COMPONENT.HTML

<div *ngIf="barcodes.length > 0;else noBarcodes">
        <div *ngFor="let barcode of barcodes">
            <a (click)="viewdet(barcode.id)"><table >
                    <tr>
                        <td><h3 class="big"><b>{{barcode.vendor}}</b></h3></td>
                        <td rowspan="3"><span>&#8250;</span></td>
                    </tr>
                    <tr>
                        <td><h3><b>Reel No:</b> {{barcode.reelno}}</h3></td>
                    </tr>
                    <tr>
                        <td><h3><b>Date:</b> {{barcode.date}}</h3></td>
                    </tr>


            </table></a>
        </div>
    </div>

【问题讨论】:

  • this.barcodeService.getBarcodes().pipe(map(barcodes =&gt; barcodes.slice().sort((x, y) =&gt; new Date(x.date).valueOf() - new Date(y).valueOf()))).subscribe(barcodes =&gt; {this.barcodes = barcodes})
  • 能否请您作为答案发布,我无法理解在哪里使用此代码
  • 这是您的ngOnInit() 的正文。它是如此微不足道,我不打算测试它。这个想法是对条形码进行排序。
  • 得到这个error TS2339: Property 'map' does not exist on type 'Observable&lt;Barcode[]&gt;'.
  • 我有一个错字,已修复

标签: angular typescript firebase google-cloud-firestore


【解决方案1】:

根据documentation,以下应该可以工作(但未经测试):

  getBarcodes(){
    this.barcodes = this.afs.collection('barcodes', ref => ref.orderBy('date')).valueChanges();
    return this.barcodes;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    相关资源
    最近更新 更多