将 rxjs Observable 序列化为自定义业务对象
Serializing rxjs Observable to custom business objects
如何序列化通过对我的业务对象的 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 运算符让我实现了这个?
我的生意class是:
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>
一个简单的附加 .map
,您可以在其中映射每个数组条目:
this.myData$ = this._http.get('/data/myData.json')
.map(response => <any[]>response.json())
.map(items => items.map(item => new Custom(item));
如何序列化通过对我的业务对象的 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 运算符让我实现了这个?
我的生意class是:
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>
一个简单的附加 .map
,您可以在其中映射每个数组条目:
this.myData$ = this._http.get('/data/myData.json')
.map(response => <any[]>response.json())
.map(items => items.map(item => new Custom(item));