我正在为我在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),但是我得到了错误&#flatctMap不是函数' (顺便说一句,我已经导入了运算符mergeMap)。 我还想知道 this.members 定义为 MyRecord 数组可以接受不同的类型。
答案 0 :(得分:3)
这似乎是一个问题:
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)));
}, []);
}
它应该做的事情。
答案 1 :(得分:2)
response.json()
返回一个普通对象,而不是一个可观察对象。从那时起,您将使用标准的Array方法在一个简单的Array上运行,该方法不包括flatMap
。
您可以使用Observable.from
将其转换为可观察对象,但根据您在示例中执行的操作,我没有看到这样做的重点。只需使用不同的策略来映射/减少该数组。