簡體   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