【问题标题】:how to acces to property inside json using angular如何使用角度访问json内部的属性
【发布时间】:2021-09-28 16:13:38
【问题描述】:

我只是想访问我的 json 中的一个键,但我不能,我不明白我的错误。因为否则我有一个 [object object]。

我也知道,如果我使用 keyvalue 管道,我当前的代码可以在我不访问颜色键的情况下工作。

我遇到的错误是:类型'Itoto []'上不存在属性'color'

json

{
  "color": [ // I want to access to color
   [
    "1", 
    "red",
    "green"
   ]
  ]
}

ts.file

get() {
 this.service.get().subscribe((data: Itoto[])=> {
  this.array = data.color //i try this but i have property color does not exist on type 'Itoto[]'
 });

界面

export interface Itoto {
 color:[
 id:number
 ]
}

【问题讨论】:

  • 你正在接收一个数组,所以你需要映射。 data.map(item => console.log(item.color));
  • 颜色在类型 Itoto ARRAY 上不存在。颜色在 data[0].color.
  • 看来您在data: Itoto[] 处签错了类型。应该是data: Itoto

标签: javascript json angular typescript


【解决方案1】:

您必须确定是否需要接收Itoto[] 的数组,还是只需要一个Itoto

所以我认为你有两种解决方案:

第一个解决方案:映射到您收到的数据。

this.service.get().subscribe((data: Itoto[])=> {
  this.array = data.map(item => item.color);
});

第二个解决方案:返回单个Itoto

this.service.get().subscribe((data: Itoto)=> {
  this.array = data.color;
});

编辑 1

我在 Stackblitz 上重现了您的代码,但很多事情似乎都是错误的。 实际上,根据 JSON 和 get() 方法,您希望使用单个 Itoto。您必须映射 color 属性。

所以这里是 ts :


export interface Itoto {
  color: string[][];
}

array: Itoto;

res: Itoto = {
  "color": 
   [[
    "1", 
    "red",
    "green"
  ]]
};

constructor() {
  this.get().subscribe((data: Itoto) => {
    this.array = data;
  });
}

get(): Observable<Itoto> {
  return of(this.res);
}
<div *ngFor="let color of array.color">
  <p>The array : {{ color | json }}</p>
  Single values :  <span *ngFor="let item of color">{{ item | json }}</span>
</div>

这是一个有效的 Stackblitz:https://stackblitz.com/edit/angular-ivy-11c8h4?file=src/app/app.component.html

【讨论】:

  • 对于第二个解决方案我有这个错误:type '[id:number]' is not assignable to type 'Itoto[] type number is not assignable to type 'Itoto
  • @Jean this.data 的类型是什么?
【解决方案2】:

如果您的 json 中只有颜色属性,那么您将直接在响应中获得颜色。您需要将响应类型 Itoto[] 更改为 Itoto。

.ts 文件

get() {
 this.service.get().subscribe((data: Itoto)=> {
  this.array = data.color; //color as data
 });

我从响应中控制数据,您可以看到结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2020-08-12
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    相关资源
    最近更新 更多