RxJS / Angular:如何压缩可观察的对象数组 [英] RxJS/Angular: How to zip observable arrays of objects

查看:100
本文介绍了RxJS / Angular:如何压缩可观察的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用离子2和角度2.现在我有两个包含对象数组的observable并传递给我的模板进行显示:

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:

用户:Observable< User []> ;;
得分:Observable<得分[]> ;;

在我的模板中,我目前必须单独显示它们:

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>

但是,我希望能够一起显示这些值,user.id和score.total ,在同一条线上。目前它显示所有分数,然后显示所有用户ID。 Observable数组始终包含相同数量的项。

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.

用户和分数的模型是:

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

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

使用Aravind答案的示例邮政编码:

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

将三个对象打印到控制台,这是正确的对象数。但是每个都是Object {id:Array [0],total:Array [0]}

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

推荐答案

猜猜下面的代码可以帮到你

Guess the below code helps you

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

注意:如果这不起作用,则需要样本json查找特定属性。根据我可以更新

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

这篇关于RxJS / Angular:如何压缩可观察的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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