【发布时间】: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