Querying data from AngularFire2 with combinelatest

筅森魡賤 提交于 2019-12-25 07:27:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!