问题
I could achieve some filtering behaviour with my question querying subset from angularfire2. Now I want to display these values as a list in Angular using ngFor. In my ts file I have:
export class OtherAnimals{
public animalList: Observable<{}>;
constructor(public af: AngularFire) {
this.animalList = Observable.combineLatest(
this.af.database.object('/set1/'),
this.af.database.object('/set2/'),
// Use the operator's project function to emit an
// object containing the required values.
(set1, set2) => {
let result = {};
Object.keys(set1).forEach((key) => {
if (!set2[key]) {
result[key] = this.af.database.object('/allanimals/' + key);
}
});
return result;
}
);
}
}
and in my .html
file I have:
<ul>
<li *ngFor="let item of animalList | async">{{item.name}}</li>
</ul>
回答1:
Might be worth it to build out a sub component that takes an animalId
which will then go fetch animal information for you, and then display it. That way you can reuse it in other places. Also you won't have to build out crazy switchMaps or some other complex Observable patterns to solve all in one go.
other-animals.component.html
<ul>
<li *ngFor="let animalId of animalList | async">
<animal-item [animalId]="animalId"></animal-item>
</li>
</ul>
other-animals.component.ts
export class OtherAnimalsComponent {
private animalKeys: Observable<any>;
constructor(public af: AngularFire) {
this.animalKeys = Observable.combineLatest(
this.af.database.object('/set1'),
this.af.database.object('/set2'),
(set1, set2) => {
let list = [];
Object.keys(set1).forEach((key) => {
if (!set2[key]) { list.push(key); }
});
return list;
}
);
}
animal-item.component.html
<span>{{ (animalInfo | async)?.name }}</span>
animal-item.component.ts
@Component({
selector: 'animal-item',
templateUrl: 'animal-item.component.html'
})
export class AnimalItemComponent implements OnInit {
@Input() animalId: string;
animalInfo: Observable<any>;
constructor (private af: AngularFire) {}
ngOnInit () {
this.animalInfo = this.af.database.object(`/allanimals/${animalId}`);
}
}
来源:https://stackoverflow.com/questions/39652200/querying-data-from-angularfire2-with-combinelatest