【问题标题】:How to access array inside array of object in Angular7?如何在Angular7中访问对象数组内的数组?
【发布时间】:2019-06-24 18:11:42
【问题描述】:

我正在使用 Angular7 并且有一个自定义类,其中包含一个数字和一个字符串数组。

export class Page {
constructor(id: number, keywords: string[]) {}
}

现在我在我的组件中创建了这个对象的数组并对其进行了初始化。

import {Page} from '../page';
export class SearchComponent implements OnInit {
 pages: Page [];
 constructor() { }
 ngOnInit() {
 this.pages = [
  {id:'1', Keywords:['abc', 'bca','klj']},
  {id:'2', Keywords:['asas', 'aaa']},
  {id:'3', Keywords:['dasd', 'asd']}
  ];
  consol.log(this.pages[0].keywords);
  consol.log(this.pages[0].id);
 }
}

我想访问id 和关键字数组,但是这段代码显示编译错误:

类型“页面”和属性“关键字”上不存在属性“id” 类型“页面”上不存在。

【问题讨论】:

  • page.ts 中,将代码替换为:export interface Page { id: string, keywords: string[] }。然后注意keywords的情况。
  • 成功了。太感谢了。但是为什么我不能把它当作一个类来使用呢?
  • 你可以。然后你必须使用构造函数:this.pages = [new Page(1, ["a", "b"]), new Page(2, ["c", "d"])]。然后在 Page 的构造函数中,您必须通过添加 public 访问器将参数保留为属性:constructor(public id: number, public keywords: string[]) {}

标签: angular typescript angular7


【解决方案1】:

这确实是初学者的问题,但是……以下是解决方案:

使用接口

定义接口:

export interface Page {
  id: number
  keywords: string[]
}

然后,使用它:

this.pages = [
  { id: 1, keywords: ['a', 'b'] },
  { id: 2, keywords: ['c', 'd' }
]

使用类

定义类:

export class Page {
  constructor(public id: number, public keywords: string[]) {}
}

然后,使用它:

this.pages = [
  new Page(1, ['a', 'b']),
  new Page(2, ['c', 'd'])
]

【讨论】:

    【解决方案2】:

    在您的代码中,您正在初始化this.pagesid 作为 字符串keywords 作为 字符串 的数组。

    所以你必须定义一个接口Page

    export interface Page {
      id: string;
      keywords: string[];
    }
    

    并像这样使用它,将Keywords 更改为keywords

    this.pages = [
      {id: '1', keywords:['abc', 'bca','klj']},
      {id: '2', keywords:['asas', 'aaa']},
      {id: '3', keywords:['dasd', 'asd']}
    ];
    

    如果您想将id 属性作为数字,请这样做:

    export interface Page {
      id: number;
      keywords: string[];
    }
    and use it like that, changing Keywords to keywords:
    
    this.pages = [
      {id: 1, keywords:['abc', 'bca','klj']},
      {id: 2, keywords:['asas', 'aaa']},
      {id: 3, keywords:['dasd', 'asd']}
    ];
    

    如果你想要一个 class 而不是 interface,请查看@Paleo 答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多