使用Angular 2,我从服务接收JSON数据。像这样:
{
"customerName": "foo",
"customerAddress": "123 Somewhere",
"products":
[
{
"productName": "bar",
"productNumber": 123
},
{
"productName": "baz",
"productNumber": 456
}
]
}
在我的组件中,我订阅了服务以填充customerData
。
private _getData() {
this._myService
.getData()
.subscribe(
customerData => this.customerData = customerData,
error => this.errorMessage = error
);
}
此代码可以正常工作。
在JSON转储中,有两个数据“分组”,即客户数据和产品数据,后者在数组中。理想情况下,我想分别填充产品数据。像这样:
.subscribe(
customerData => this.customerData = customerData,
productData => this.productData = customerData.products
error => this.errorMessage = error
);
这可能,如果可以,我将如何编码订阅?
答案 0 :(得分:7)
你可以写订阅
subscribe(
customerData =>
{
this.customerData = customerData;
this.productData =customerData.products;
},
error => this.errorMessage = error
);
或
subscribe(
function(customerData)
{
this.customerData = customerData;
this.productData =customerData.products;
},
error => this.errorMessage = error
);
答案 1 :(得分:2)
您可以在subscribe()
回调中分割数据:
private _getData() {
this.customerData = {};
this.productData = {};
this._myService.getData().subscribe(data => {
Object.keys(data).forEach(key => {
if(key.startsWith("customer")) {
this.customerData[key] = data[key];
} else {
this.productData[key] = data[key];
}
});
});
}
请注意,IE不支持startsWith()
。
或者您可以拆分服务中的数据。一种方法是:
custData$
,prodData$
http.get()
可观察对象,并如上所示拆分数据this.custData$.next(this.customerData)
和this.prodData$.next(this.productionData)
发出数据custData$
,prodData$
答案 2 :(得分:0)
我想要分离的每个数据都有一个可观察对象,如下所示:
<强>服务强>
private getDataFromHttp() {
return this._http
.get(this.url)
.map(res => res.json())
.do(data => {
console.log(data);
});
}
public getCustomerData() {
getDataFromHttp()
.map(res => res.customerData)
}
public getProductData () {
getDataFromHttp()
.map(res => res.productData)
}
组件
private _getData() {
this._myService
.getCustomerData()
.subscribe(
customerData => this.customerData = customerData,
error => this.errorMessage = error
);
}
private _getData() {
this._myService
.getProductData()
.subscribe(
productData => this.productData = productData,
error => this.errorMessage = error
);
}
此示例将为每个函数调用生成一个http请求,HERE是另一篇文章,说明我如何缓存observable,以便每次都不从服务器请求数据:caching results with angular2 http service