繁体   English   中英

使用RXJS的Typescript展平数组

[英]Typescript flatten array with RXJS

我为Ionic 2应用程序中的RXJS转换遇到的问题而震惊。 我想将一个json文件放到对象中,这是我的简化json文件

    [{
     "lingua": "it",
     "labels": {
        "denominazione": "Hi",
     },
     "tipologie": [
      {"denominazione": "test 1"},
      {"denominazione": "test 2"}
    ]
    },...]

这是打字稿代码的片段

    export class MyRecord{
       denominazione: string;
       label_denominazione: string;

       constructor(denominazione: string, label_denominazione: string) {
          this.denominazione = denominazione;
          this.label_denominazione = label_denominazione;
       }
    }

    public getRecords() {
       var url = '../assets/records.json'; 
       let records$ = this.http
          .get(url)
          .map(mapRecords);
    return records$;

    function mapRecords(response: Response): MyRecord[] {
       return response.json().filter(x => x.lingua == "it")
        .map(({ lingua, labels, tipologie }) => tipologie.map(tipologia =>
        toMyRecord(labels, tipologia))
       );
    }

    function toMyRecord(l: any, t: any): MyRecord{
      let record= new MyRecord(
        t.denominazione,
        l.denominazione,
      );
      return record;
    }

当我致电服务时:

    members: MyRecord[];
    this.myService.getRecords().subscribe(res => {
        this.members = res;
        },
        err => console.log(err)
    );

我得到this.membersMyRecord的数组的数组:

    [[{ label_denominazione: "Hi", denominazione: "test 1"}, { label_denominazione: "Hi", denominazione: "test 2"} ]]

而不是MyRecord的数组:

    [{ label_denominazione: "Hi", denominazione: "test 1"}, { label_denominazione: "Hi", denominazione: "test 2"} ]

我尝试使用flatMap(mergeMap),但出现错误“ flatMap不是函数”(顺便说一句,我已经导入了操作符mergeMap)。 我也想知道的定义如MyRecord阵列this.members可以接受不同的类型。

这似乎是一个问题:

function mapRecords(response: Response): MyRecord[] {
   return response.json().filter(x => x.lingua == "it")
    .map(({ lingua, labels, tipologie }) => tipologie.map(tipologia =>
    toMyRecord(labels, tipologia))
   );
}

而不是第一个map尝试像这样进行reduce ,它将合并映射:

function mapRecords(response: Response): MyRecord[] {
   return response.json().filter(x => x.lingua == "it")
      .reduce((result, current, idx) => 
          result.concat(current.topologie.map(tipologia =>
              toMyRecord(current.labels, tipologia)));
      }, []);
}

它应该做的事情。

response.json()返回一个普通对象,而不是一个可观察对象。 从那时起,您将使用不包含flatMap的标准Array方法在一个简单的Array上进行操作。

您可以使用Observable.from将其转换为Observable.from但基于示例中的操作,我认为这样做没有意义。 只需使用其他策略即可映射/减少该数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM