使用 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.members中得到的是MyRecord:

的数组
    [[{ 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 is not a function'(顺便说一句,我已经导入了运算符 mergeMap)。 我也想知道 this.members 定义为 MyRecord 数组可以接受不同的类型。

这里好像有问题:

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() returns 一个普通对象,而不是一个可观察对象。从那时起,您将使用标准数组方法对简单数组进行操作,其中不包括 flatMap.

您可以使用 Observable.from 将其转换为可观察对象,但根据您在示例中执行的操作,我看不出这样做有什么意义。只需对 map/reduce 该数组使用不同的策略。