使用 combinelatest 从 AngularFire2 查询数据

Querying data from AngularFire2 with combinelatest

我可以通过我的问题 实现一些过滤行为。现在我想使用 ngFor 将这些值显示为 Angular 中的列表。在我的 ts 文件中,我有:

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;
            }
        );
    }
}

在我的 .html 文件中我有:

<ul>
<li *ngFor="let item of animalList | async">{{item.name}}</li>
</ul>

构建一个子组件可能是值得的,该子组件采用 animalId,然后为您获取动物信息,然后显示它。这样你就可以在其他地方重复使用它。此外,您不必构建疯狂的 switchMaps 或其他一些复杂的 Observable 模式来一次性解决所有问题。

其他-animals.component.html

<ul>
  <li *ngFor="let animalId of animalList | async">
    <animal-item [animalId]="animalId"></animal-item>
  </li>
</ul>

其他-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;
      }
    );
}

动物-item.component.html

<span>{{ (animalInfo | async)?.name }}</span>

动物-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}`);
  }
}