我正在尝试过滤从firebase firestore检索到的集合(借助于angularfire2)。问题是我什么都没进入过滤列表。
这是我的代码:
import { Component, OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable, BehaviorSubject, combineLatest } from 'rxjs';
import { Company } from '../../shared/models';
import { ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
import * as _ from 'lodash';
import { Subject } from 'rxjs';
import { switchMap, map} from 'rxjs/operators';
@Component({
selector: 'app-companies',
templateUrl: './companies.component.html',
styleUrls: ['./companies.component.scss']
})
export class CompaniesComponent implements OnInit {
filters = {}
private companiesCollection: AngularFirestoreCollection<Company>;
companies: any;
filteredCompanies: any;
constructor(private readonly afs: AngularFirestore) {
this.companiesCollection = afs.collection<Company>('companies');
this.getCompanies().subscribe(() => {
this.applyFilters();
});
}
ngOnInit() {
}
getCompanies() {
return this.companies = this.afs.collection<Company>('companies').valueChanges();
}
/// filter properties that resolve to true
filterBoolean(property: string, rule: boolean) {
if (!rule) this.removeFilter(property)
else {
this.filters[property] = val => val
this.applyFilters()
}
}
private applyFilters() {
this.filteredCompanies = _.filter(this.companies, _.conforms(this.filters) )
}
<div class="field">
<input type="checkbox" (change)="filterBoolean('firstCondition', $event.target.checked)"> True or false 1?
</div>
<div class="field">
<input type="checkbox" (change)="filterBoolean('secondCondition', $event.target.checked)"> True or false 2?
</div>
<div class="field">
<input type="checkbox" (change)="filterBoolean('secondCondition', $event.target.checked)"> True or false 3?
</div>
<!-- (WORKING): Displays all the companies names -->
<div *ngFor="let company of companies | async">
<h6>{{ company.name }}</h6>
</div>
<!-- (NOT WORKING): Displays all the filtered companies -->
<div *ngFor="let filteredCompany of filteredCompanies">
<h6>{{ filteredCompany.name }}</h6>
</div>
Angular 6,angularfire2(v.5),lodash(v.4)。
我是否以某种方式使数据结构不匹配? 有人可能对此有解决方案吗?
我正在关注this tutorial from Jeff Delaney,并在本文的“选项1-客户端过滤”下尝试适应Firestore而非实时数据库。
任何能使我更接近目标的帮助将不胜感激。
DeborahK的回答帮助我解决了这个问题。
在构造函数中更改为:
this.getCompanies().subscribe(companies => {
this.companies = companies; // <== Added this line
this.applyFilters();
});
函数getCompanies()
用于:
// Now only returns the retrieved collection
getCompanies() {
return this.afs.collection<Company('companies').valueChanges();
}
答案 0 :(得分:0)
this.companies
设置在哪里?看来您正在将其传递到过滤器中,但未在任何位置进行设置。
this.filteredCompanies = _.filter(this.companies, _.conforms(this.filters) )
请注意,在上面的代码中,您正在使用this.companies
作为过滤的源。如果未设置,则不会有任何经过过滤的公司。
该代码应为:
this.getCompanies().subscribe(() => {
this.applyFilters();
});
也许是这个吗?
this.getCompanies().subscribe(companies => {
this.companies = companies;
this.applyFilters();
});