【问题标题】:Querying data from AngularFire2 with combinelatest使用 combinelatest 从 AngularFire2 查询数据
【发布时间】:2017-01-31 19:23:48
【问题描述】:

我可以通过我的问题querying subset from angularfire2 实现一些过滤行为。现在我想使用 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>

【问题讨论】:

  • 看起来唯一缺少的是大括号:..."&gt;{{ item.name }}&lt;/li&gt;
  • 这是一个错字@cartant,刚刚在问题中修正

标签: firebase firebase-realtime-database angularfire2


【解决方案1】:

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

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

【讨论】:

  • 我想过这一点,但我已经将搜索绑定到父列表,所以如果我这样做,我将不得不始终将值推回服务中,这比使用 combine latest 更痛苦。 ..
猜你喜欢
  • 2018-06-14
  • 1970-01-01
  • 2018-02-19
  • 2023-03-17
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 2018-06-22
  • 2018-04-21
相关资源
最近更新 更多