typescript Angular使用来自API调用的JSON数据

oiopk7p5  于 7个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(94)

我从一个后端Web服务中获取以下JSON数据。

[
    {
        "id": 10,
        "name": "My Name1",
        "age": 25,
        "jsonData": null
    },
    {
        "id": 15,
        "name": "My Name2",
        "age": 25,
        "jsonData": "{\"Address\":\"My Address 123\",\"City\":\"My City\",\"PostalCode\":\"ABC-123-DEF\",\"Country\":\"My Country\"}"
    }
]

字符串
我可以用ngFor在组件html上循环数组没有问题,但我如何读取“jsonData”字段,如“地址”,“城市”等?

谢谢你的回答!

我从component.ts调用的API是这样的:

async getAllUsers() {
    this.allUsers = [];

    this.allUsers = await lastValueFrom(
        await this.service.getAllUsers()
    );

    this.allUsers.forEach((node) => {
        node.jsonData = JSON.parse(node.jsonData);
    });
}


然后在我的html中,我这样做:

{{ node.jsonData.Address }}

sdnqo3pr

sdnqo3pr1#

您需要将jsonDatastring转换为JSON.parse(<JSON string>)对象类型。
请注意,这可以在通过map(RxJS)操作符返回Observable/响应期间执行。
请注意,您的jsonData可能是null,因此您必须在转换之前检查jsonData是否正确。

import { map } from 'rxjs';

this.http.get<any[]>('<API URL>').pipe(
  map((resp: any[]) =>
    resp.map((x: any) => ({
      ...x,
      jsonData: !!x.jsonData ? JSON.parse(x.jsonData) : null,
    }))
  )
);

字符串
Demo @ StackBlitz

kq0g1dla

kq0g1dla2#

尝试对字符串化的json对象使用JSON.parse()。在try catch块中使用JSON.parse,以便如果传递的jsonData有格式问题,您可以捕获它并在catch块中执行必要的步骤。
如果您使用Rxjs,请尝试使用map操作符,以便将响应Map到您想要的特定格式。@Yong Shun已经为您展示了方法。您可以从rxjs尝试catchError,以便更优雅地处理可观察链中的任何错误。

相关问题