Angular 角度|无法读取属性';XXX和x27;未定义的
我使用了2个model.ts profile.model.tsAngular 角度|无法读取属性';XXX和x27;未定义的,angular,typescript,properties,model,Angular,Typescript,Properties,Model,我使用了2个model.ts profile.model.ts export interface Profile { username: string; nickname: string; image: string; } import { Profile } from '.'; export interface Comment { author: Profile; content: string; creatat?: Date; } ... exp
export interface Profile {
username: string;
nickname: string;
image: string;
}
import { Profile } from '.';
export interface Comment {
author: Profile;
content: string;
creatat?: Date;
}
...
export class CommentComponent implements DoCheck {
...
content: string; // Get value from ngModel in comment.component.html
comments: Comment; // comment.model.ts
}
...
addComment() {
this.comments.author.nickname = 'Test Nickname';
this.comments = {
content: this.content
};
...
}
'comment.model.ts'使用'profile.model.ts' comment.model.ts
export interface Profile {
username: string;
nickname: string;
image: string;
}
import { Profile } from '.';
export interface Comment {
author: Profile;
content: string;
creatat?: Date;
}
...
export class CommentComponent implements DoCheck {
...
content: string; // Get value from ngModel in comment.component.html
comments: Comment; // comment.model.ts
}
...
addComment() {
this.comments.author.nickname = 'Test Nickname';
this.comments = {
content: this.content
};
...
}
comment.component.ts
export interface Profile {
username: string;
nickname: string;
image: string;
}
import { Profile } from '.';
export interface Comment {
author: Profile;
content: string;
creatat?: Date;
}
...
export class CommentComponent implements DoCheck {
...
content: string; // Get value from ngModel in comment.component.html
comments: Comment; // comment.model.ts
}
...
addComment() {
this.comments.author.nickname = 'Test Nickname';
this.comments = {
content: this.content
};
...
}
当我运行addComment()时,出现以下错误 错误类型错误:无法读取未定义的属性“author” 有什么问题
提前感谢您的建议。您需要初始化
注释
属性。目前您只设置了它的类型-Comment
因为Profile
的属性不是可选的,所以您需要显式地将它们分配给null
s
comments: Comment = {
author: {
username: null,
nickname: null,
image: null,
},
content: null
}
或者,您可以在属性名称之后添加?
,使它们成为可选的
export interface Profile {
username?: string;
nickname?: string;
image?: string;
}
然后像这样初始化
comments: Comment = {
author: { }
}