我正在按角度使用Firestore,我想显示按属性pos
排序的集合,导入集合没有问题,但是我不知道如何排序。
我尝试遵循一些使用功能orderBy('pos')
的教程,但是控制台返回了我:
ERROR TypeError: this.competence.orderBy is not a function
at FirebaseService.fireBaseRequest (main.js:401)
at FirebaseService.getCompetence (main.js:405)
at HomePageComponent.getComp (main.js:298)
at HomePageComponent.ngOnInit (main.js:305)
at checkAndUpdateDirectiveInline (vendor.js:87496)
at checkAndUpdateNodeInline (vendor.js:98156)
at checkAndUpdateNode (vendor.js:98095)
at prodCheckAndUpdateNode (vendor.js:98949)
at Object.eval [as updateDirectives] (ng:///AppModule/Home…ost.ngfactory.js:10)
at Object.updateDirectives (vendor.js:98569)
defaultErrorLogger @ vendor.js:70180
我的firebase.service:
import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
import {AngularFirestore} from '@angular/fire/firestore';
@Injectable({
providedIn: 'root'
})
export class FirebaseService {
competence;
constructor(private firestore: AngularFirestore) {
}
fireBaseRequest(path) {
this.competence = this.firestore.collection(path);
this.competence = this.competence.orderBy('pos').get();
return this.firestore.collection(path).snapshotChanges();
getFormation() {
return this.fireBaseRequest('formations');
}
}
}
我的组件HTML:
<!-- Formation-->
<mat-card *ngFor="let formation of filterBy('pos') " class="mb-3">
<mat-card-title>
{{formation.payload.doc.data().titre}}
</mat-card-title>
<mat-card-subtitle>
{{formation.payload.doc.data().lieu}}
<p>{{formation.payload.doc.data().date}}</p>
</mat-card-subtitle>
<mat-card-content>
{{formation.payload.doc.data().description}}
</mat-card-content>
</mat-card>
我的组件ts:
import {Component, OnInit} from '@angular/core';
import {FirebaseService} from '../services/firebase.service';
@Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
competence;
formations;
getComp = () =>
this.firebaseService
.getCompetence()
.subscribe(res => (this.competence = res));
getFormation = () =>
this.firebaseService
.getFormation()
.subscribe(res => (this.formations = res));
constructor(private firebaseService: FirebaseService) {
}
ngOnInit() {
this.competence = this.getComp();
this.formations = this.getFormation();
if (window.innerWidth < 768) {
this.cols = '4';
this.rowHeight = '4:5';
}
}
答案 0 :(得分:2)
尝试这样:
我的firebase.service:
this.competence = this.firestore.collection(path, ref => ref.orderBy('pos'));
或按组件排序。
我的组件ts:
getComp = () =>
this.firebaseService
.getCompetence()
.subscribe(res => (this.competence = this.sortArrayByKey(res,'pos'));
并添加sortArrayByKey
函数:
sortArrayByKey(Array:any[], Key:string) {
return Array.sort(function (a, b) {
return a[Key] - b[Key];
});
}