Arrays 如何从json中的数组中获取数据?

Arrays 如何从json中的数组中获取数据?,arrays,json,angular,dictionary,object,Arrays,Json,Angular,Dictionary,Object,我如何从这个json中获取信息,以便在angular 10中绘制它们 { "countries": [ { "id": 1, "name": "United States" }, { "id": 2, "name": "India" } ], "stat

我如何从这个json中获取信息,以便在angular 10中绘制它们

{
  "countries": [
    {
      "id": 1,
      "name": "United States"
    },
    {
      "id": 2,
      "name": "India"
    }
 
  ],
  "states": [
    {
      "id": 1,
      "countryId": 1,
      "name": "Alabama"
    },
    {
      "id": 2,
      "countryId": 1,
      "name": "Alaska"
    }
  ]
}
对于普通的JSON,我使用了这个,但是jeson有2个数组,它不允许我使用

return this.http.get<Country[]>("./assets/data.json");
还有我的订阅

countri: Country[] = [];

  this.countriesService.getCountries().subscribe(
      countri => {
        this.countri = countri;
        console.log(countri);
      },
      err => console.log(err)
       );

使用
any

第一条路:


上述错误(尝试区分“[object]”时出错)是因为您在模板中的某个位置使用此json,但它没有值。希望它能修复它或提供模板代码。

尝试区分“[object]”时出错。只允许使用数组和iterables
,当您尝试使用对象而不是数组迭代ngFor时,通常会出现此错误

如果您使用的是ngFor

list.component.ts

data={
  "countries": [
    {
      "id": 1,
      "name": "United States"
    },
    {
      "id": 2,
      "name": "India"
    }

  ],
  "states": [
    {
      "id": 1,
      "countryId": 1,
      "name": "Alabama"
    },
    {
      "id": 2,
      "countryId": 1,
      "name": "Alaska"
    }
  ]
}
list.component.html

<ul>
    <li *ngFor="let item of data.countries">
        {{item.name}}
    </li>
</ul>
    {{item.name}

    {{item.name}
正如错误所示,您很可能试图迭代对象而不是数组。此外,由于获取的数据是异步的,因此可以使用以下代码来避免任何错误。它使用异步管道和安全(?)操作符

.ts

模板

<div *ngFor="let country of (jsonData | async)?.countries">
    {{ country | json}}
</div>

<div *ngFor="let state of (jsonData | async)?.states">
    {{ state | json}}
</div>

{{国家| json}
{{state | json}}

数据是异步获取的,因此上面的解决方案将破坏模板。@Tony-您需要在模板中使用异步管道。有什么答案对您有用吗?如果是的话,请考虑接受/鼓励他们。
export interface IRequest {
 countries: ICourtry[],
 states: IState[]
}

export interface ICourtry{
 id:number;
 name: string;
}

export interface IState{
 id:number;
 name: string;
 countryId: number;
}

return this.http.get<IRequest>("./assets/data.json");
data={
  "countries": [
    {
      "id": 1,
      "name": "United States"
    },
    {
      "id": 2,
      "name": "India"
    }

  ],
  "states": [
    {
      "id": 1,
      "countryId": 1,
      "name": "Alabama"
    },
    {
      "id": 2,
      "countryId": 1,
      "name": "Alaska"
    }
  ]
}
<ul>
    <li *ngFor="let item of data.countries">
        {{item.name}}
    </li>
</ul>
<ul>
  <li *ngFor="let item of data.states">
           {{item.name}}
  </li>
jsonData;

ngOnInit() {
   this.jsonData = this.http.get('./assets/data.json');
}
<div *ngFor="let country of (jsonData | async)?.countries">
    {{ country | json}}
</div>

<div *ngFor="let state of (jsonData | async)?.states">
    {{ state | json}}
</div>