简体   繁体   English

无法设置未定义的属性“ someProperty”-Angular Typescript

[英]Cannot set property 'someProperty' of undefined - Angular Typescript

I have a class Article which has property of type Image and looks like this: 我有一个Article类,它具有Image类型的属性,看起来像这样:

export class Article {
   public image:Image;
   public images: Image[]; 
}

If I comment this.article.image = new Image(); 如果我评论this.article.image = new Image(); like this: 像这样:

constructor()
{
    this.article = new Article();
    //this.article.image = new Image();
}

And If I try to use an this.image later in code, like: 如果我稍后在代码中尝试使用this.image,例如:

 this.article.image.fileName = file.name;

I will get following error: 我将收到以下错误:

ERROR TypeError: Cannot set property '..' of undefined 错误TypeError:无法设置未定义的属性“ ..”

But I realized in case when I try to add something to an array for example: 但是我意识到,以防万一,当我尝试向数组中添加某些内容时:

this.article.images.push(something);

I am not getting error! 我没有收到错误! And I'm wondering why I don't get error when I use array (even if I did not said this.article.images = new Images[].. , and why I get error when I'm using simple object/not array.. 而且我想知道为什么我在使用数组时不会出错(即使我没有说this.article.images = new Images[].. ,以及为什么在我使用简单对象/非时我都会出错?数组..

I guess the .. in your error code means fileName . 我想您错误代码中的..表示fileName

You actually explained the error yourself. 您实际上是自己解释了该错误。

If I comment this.article.image = new Image();

You removed the creation of your image, thus, this.article.image is undefined. 您删除了图像的创建,因此this.article.image是未定义的。

So by using this.article.image.fileName , you are trying to access the property fileName of undefined . 因此,通过使用this.article.image.fileName ,您尝试访问undefined的属性fileName

However, for the property images , the method .push() already exists because it's a method defined by Array , which is known thanks to the declaration : 但是,对于属性images ,方法.push()已经存在,因为它是Array定义的方法,该方法由于声明而众所周知:

public images: Image[];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM