如何对通过http调用返回给我的业务对象的rxjs observable进行序列化?样品在下面提到
myData.json:
[{
"prop1" : "val1",
"prop2" : "val2",
"prop3" : "val3",
"prop4" : "val4",
}, {
"prop1" : "val11",
"prop2" : "val22",
"prop3" : "val33",
"prop4" : "val44",
},......]
可观察的:
this.myData$ = this._http.get('/data/myData.json')
.map(response => <any[]>response.json());
模板:
<ul>
<li class="text" *ngFor="let item of myData$ | async">
{{item.prop1}} - {{item.prop2}} - {{item.prop3}}
</li>
</ul>
上面的代码一切都很好,但是我需要将异步接收到的JSON对象转换为其他业务对象的实例,并且仍然异步绑定到模板。我该如何做到这一点。哪个rxjs运算符让我实现了这一目标?
我的商务舱是:
export class Custom {
prop10: string;
prop20: string;
constructor(data) {
this.prop10 = this.evaluate(data.prop1);
this.prop20 = data.prop2;
}
private evaluate(val): string {
// do some custom business rules....
return "something";
}
}
我的实际模板
<ul>
<li class="text" *ngFor="let item of myData$ | async">
{{item.prop10}} - {{item.prop20}}
</li>
</ul>
一个简单的Additional .map
,您可以在其中映射每个数组条目:
this.myData$ = this._http.get('/data/myData.json')
.map(response => <any[]>response.json())
.map(items => items.map(item => new Custom(item));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句