使用 combinelatest 从 AngularFire2 查询数据 [英] Querying data from AngularFire2 with combinelatest

查看:25
本文介绍了使用 combinelatest 从 AngularFire2 查询数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过我的问题从 angularfire2 查询子集来实现一些过滤行为.现在我想使用 ngFor 在 Angular 中将这些值显示为列表.在我的 ts 文件中,我有:

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

在我的 .html 文件中:

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

推荐答案

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

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

这篇关于使用 combinelatest 从 AngularFire2 查询数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆