我有一个待办事项列表,并希望按诸如“ author / dateOfCreate / deadline ..”等类别对其进行排序。 我在第一次使用Firebase orderBy('property_name')方法时在构造函数中调用它-它可以工作,但是当我尝试在下面的函数中传递不同的'property_name'时,它却没有。 我对此并不陌生,因此将为您提供任何建议。 这是我的代码:
export interface Todo {
id?: string,
author?: string,
completed?: boolean,
dateOfCreate?: number,
deadline?: number,
todoDescription?: string
}
TodoService
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument
} from '@angular/fire/firestore';
import { Todo } from '../models/todo'
import { Observable } from 'rxjs';
import { map, filter } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class TodosService {
todoCollection: AngularFirestoreCollection<Todo>
todos: Observable<Todo[]>
sort: string= 'deadline'
constructor(public afs: AngularFirestore) {
console.log(this.afs.collection('todos'))
this.todoCollection = this.afs.collection('todos', ref => ref.orderBy(this.sort, 'desc'))
this.todos = this.todoCollection.snapshotChanges().pipe(
map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as Todo
data.id = a.payload.doc.id
return data
})
})
)
}
getTodos() {
return this.todos
}
sortByAuthor(){
return this.sort = 'author'
}
}
Todo.component.ts
constructor(private todoService: TodosService) { }
sortbyAuthor() {
this.todoService.sortByAuthor()
}
Todo.component.html
<button (click)="sortbyAuthor()">Author</button>
答案 0 :(得分:0)
调用sortByAuthor()
时,查询未在运行,您只是将author
分配给this.sort
。这就是为什么没有变化的原因。您可以将服务类更改为以下内容:
@Injectable({ providedIn: 'root' })
export class TodosService {
todoCollection: AngularFirestoreCollection<Todo>
todos: Observable<Todo[]>
sort: string= 'deadline'
constructor(public afs: AngularFirestore) {
console.log(this.afs.collection('todos'));
}
getCollection(sort : string){
this.todoCollection = this.afs.collection('todos', ref => ref.orderBy(this.sort, 'desc'))
this.todos = this.todoCollection.snapshotChanges().pipe(
map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as Todo
data.id = a.payload.doc.id
return data
})
})
)
}
getTodos() {
return this.todos
}
sortByAuthor(){
this.sort = 'author';
return this.getCollection(this.sort);
}
}