【问题标题】:Angular2 / Typescript "map" two observables to one InterfaceAngular2 / Typescript将两个可观察对象“映射”到一个接口
【发布时间】:2017-03-01 18:11:53
【问题描述】:

我在将两个数据源合并到一个界面时遇到了一个小问题

有一个接口

export interface IProvince {
  code: number;
  name: string;
  svgData: string;
  part: number;
  color: string;
}

现在我有两个不同的数据源,一个为我提供字段数据:[code, name, svgData, part], [color] 来自另一个 observable。

getAllProvince(): Observable<IProvince[]>
  {
    return <Observable<IProvince[]>>this.http
      .get('url')
      .map((response: Response) => <IProvince[]>response.
      .catch(this.handleError)
      .finally(() => {
        this.loader.complete();
        console.log("Data: ", this.provinceData);
      });

  }
  getLegendData(): Observable<ILegend[]> {
    return Observable.of(this.legendData);
  }

  getStyleColorData(part: number) {
    let color: ILegend;
    return this.getLegendData().subscribe((items: ILegend[]) => color = items.find(p => p.part == part));
  }

问题是目前我缺少数据 [color] 我不知道如何“即时”从另一个函数中添加值。

这里我有函数:getStyleColorData(part: number) 在我从 [getAllProvince()] 传递 [part] 之后应该给我“颜色”。 问题:有一种简单的方法可以将这两者结合起来,或者我走错了方向?

发送答案和解决方案:)

【问题讨论】:

  • this.legendData 是什么?一个简单的数组?如何从 ILegend 中获取颜色字符串?
  • 现在是数组,但应该是来自服务器的另一个数据。例如:{部分:1,名称:“Quantyl 1”,颜色:“#B4572C”},

标签: angular rxjs typescript2.0 angular2-observables


【解决方案1】:

如果您有两个 Observable(例如来自 http 请求,您可以将它们与 Observable.combineLatestObservable.withLatestFrom 结合使用。

试试这样的:

getProvinces() {
  return this.http
    .get('url')
    .map(response => response.json() as IProvince[])
    .withLatestFrom(this.getLegendData(), (provinces, legendData) => ({provinces, legendData})
    .map(combined => combined.provinces.map(
            province => province.color = combined.legendData.find(legend => legend.part == province.part).color));
}

getLegendData() {
  return this.http
    .get('url2')
    .map(response => response.json() as ILegend[]);
}

【讨论】:

  • 我试试这个,但是什么时候做这样的事情:L combineMapdata() { Observable.combineLatest(this.getAllProvince(), this.getLegendData()).subscribe((data: any[]) : void => { console.log(data); // 磁带 - data[0] // 玻璃 - data[1] }); ii 收到“控制台/服务器垃圾邮件,每秒请求一次,我相信它带有 observables 的东西
  • 我添加了一个例子,如果你尝试这样的事情时问题仍然存在,你可以试试吗?
  • 现在是:(属性 'color' 在类型 'IProvence' 上不存在。)我相信当我做“第一次映射我的颜色停止存在于上下文中时,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-02
  • 2020-02-11
  • 1970-01-01
相关资源
最近更新 更多