angular - 将对象数组转换为类实例

标签 angular typescript ecmascript-6

我从 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/

相关文章:

angular - setCenter 在 angular2-google-maps 中不起作用

javascript - 在不指定其属性的情况下解构对象

json - Ionic 4 使用搜索栏读取本地 JSON 文件

Angular 4 mat-form-field with mat-select

c# - 从控制台运行 dotnet 核心应用程序时无法解决依赖关系

Angular:ContentChild 未定义

javascript - 如何在规范文件中注入(inject)服务 Angular Testing (Jasmine/karma)

typescript - 为什么partialType 不使属性可以为空?

javascript - 通过 next() 发送参数时,ES6 生成器无法正常工作

javascript - 如何获取对象数组中键的总和并删除连续对象的重复项?