RxJS/Angular: How to zip observable arrays of obje

2019-09-07 04:55发布

问题:

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