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

oiopk7p5  于 2023-11-20  发布在  TypeScript
关注(0)|答案(2)|浏览(170)

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

  1. [
  2. {
  3. "id": 10,
  4. "name": "My Name1",
  5. "age": 25,
  6. "jsonData": null
  7. },
  8. {
  9. "id": 15,
  10. "name": "My Name2",
  11. "age": 25,
  12. "jsonData": "{\"Address\":\"My Address 123\",\"City\":\"My City\",\"PostalCode\":\"ABC-123-DEF\",\"Country\":\"My Country\"}"
  13. }
  14. ]

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

谢谢你的回答!

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

  1. async getAllUsers() {
  2. this.allUsers = [];
  3. this.allUsers = await lastValueFrom(
  4. await this.service.getAllUsers()
  5. );
  6. this.allUsers.forEach((node) => {
  7. node.jsonData = JSON.parse(node.jsonData);
  8. });
  9. }


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

  1. {{ node.jsonData.Address }}

sdnqo3pr

sdnqo3pr1#

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

  1. import { map } from 'rxjs';
  2. this.http.get<any[]>('<API URL>').pipe(
  3. map((resp: any[]) =>
  4. resp.map((x: any) => ({
  5. ...x,
  6. jsonData: !!x.jsonData ? JSON.parse(x.jsonData) : null,
  7. }))
  8. )
  9. );

字符串
Demo @ StackBlitz

展开查看全部
kq0g1dla

kq0g1dla2#

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

相关问题