我从 php 返回一个对象数组,我想将这些数据转换为 ContentData
类的实例。
我目前有以下可行的方法,但我有一种直觉,有一种更简洁的方法来实现结果。
return this.http.post("get-content.php", urlParams)
.map(this.extractData)
.map(array => {
let newArray = Array<ContentData>();
array.forEach(obj => {
newArray.push(new ContentData().deserialize(obj));
});
return newArray;
})
.catch(this.handleError)
private extractData(res: Response): any {
return res.json();
}
有没有比这样迭代数组数据更简洁的方法?
php 的响应是:
[
{"id":"1","dock_id":"46","type":"TEXT","content":"{\"text\": \"<p>test<\/p>\"}","last_updated":"2017-08-09 03:10:28","json":null},
{"id":"2","dock_id":"46","type":"TEXT","content":"{\"text\": \"<p>test test<\/p>\"}","last_updated":"2017-08-09 03:10:28","json":null}
]
预期输出为 [ContentData, ContentData, ...]
(只是一个一维数组)。
(2) [ContentData, ContentData]
0 : ContentData {content: "{"text": "<p>test</p>"}", dock_id: "46", type: 0, last_updated: "2017-08-09 03:10:28"}
1 : ContentData {content: "{"text": "<p>test test</p>"}", dock_id: "46", type: 0, last_updated: "2017-08-09 03:10:28"}
length : 2
最佳答案
如果我没看错你的代码,你可以做几件事:
- 使用
async
函数来获得更线性的代码 - 使用
.map()
代替 for-and-push
像这样:
public async fetchAndProcess(/* args */) {
try {
const res = await this.http.post("get-content.php", urlParams); // Assuming fetch
const json = await res.json();
return result = json.map(item => new ContentData().deserialize(item));
} catch (e) { this.handleError(e); }
}
我要做的另一件事是创建静态方法 ContentData.fromSerialized()
或修改 ContentData
的构造函数以接受 item
。但这更多是在代码风格领域。
关于angular - 将对象数组转换为类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45592259/