RxJS/Angular: How to zip observable arrays of objects

僤鯓⒐⒋嵵緔 提交于 2020-01-17 07:33:40

问题


I am working with ionic 2 and angular 2. Right now I have two observables that contain object arrays and are being passed to my template to be displayed:

users: Observable<User[]>; scores: Observable<Score[]>;

In my template I currently have to display them separately:

<ion-card *ngFor="let score of scores | async" >
  <ion-item text-wrap>{{ score.total }} </ion-item>
</ion-card>

<ion-card *ngFor="let user of users | async" (click)="goToPlayer(user, league)">
<ion-item text-wrap>{{ user.id }}</ion-item>
</ion-card>

However, I would like to be able to display these values together, user.id and score.total, on the same line. Currently it displays all scores and then all user ids. The Observable arrays always contain the same number of items.

The models for User and Score are:

export interface User {
id?: string,
email?: string,
leagues?: any[],
dateCreated: Date
};

export interface Score {
scores: any[],
total: number
};

Using sample zip code from Aravind's answer:

this.users = this.userData.loadUsers(this.league.id);
this.scores = this.leagueData.loadPlaylistScores(this.league.id);

Observable
.zip(this.users,
     this.scores,
     (id: number, total: number) => ({ id, total }))
.subscribe(x => console.log(x));

prints out three objects to the console, which is the correct number of objects. However each is Object {id: Array[0], total: Array[0]}


回答1:


Guess the below code helps you

Observable
    .zip(users
         scores,
         (id: number, total: number) => ({ id, total }))
    .subscribe(x => console.log(x));

Note: If this does not work, required your sample json to look for specific properties. Based on which I can update



来源:https://stackoverflow.com/questions/42352507/rxjs-angular-how-to-zip-observable-arrays-of-objects

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