2017-06-28 41 views
5

我使用的角度建立一个项目,我采用了棱角分明-CLI项目的开工,当我尝试运行ng build --prod我不断收到此错误:角4属性不上Object类型存在于构建

Property 'description' does not exist on type Object

代码生成该错误是:

export class AppComponent { 
    product: Object = {}; 

    constructor(
     private store: StoreService, 
     private request: RequestService, 
    ) { 
     this.product = this.request.getProduct(_id); 
    } 
} 

<p>{{product.description}}</p> 

我读一些有关此内容和错误是因为我使用类型定义来定义产品为对象,但我不传递任何属性定义。

我知道我可以定义一个接口,就像我对数组做的那样,但是我无法做到这一点。我不知道我是否定义错了,这是我的尝试:

export interface ProductInterface { 
    id: Number; 
    description: String; 
    title: String; 
} 

product: Object<ProductInterface> = {}; 

但它也给我错误。我需要做什么来避免这种情况?

+0

类型product'的'应该是' ProductInterface',而不是'Object '。 –

+0

谁是getProduct – alehn96

回答

4

对于你的第一个例子。在你的html中,你说产品有属性描述(它不在类型Object上)

在你的第二个例子中。您最初将产品定义为空物体

product: ProductInterface = {}; 

缺少接口的必填字段。所以,你可以删除初始化,留下

product: ProductInterface; 

也正如其他人所指出的,你不需要对象<>语法

+0

我有一个动态表单,并且在编译期间我不知道任何表单控件,在编译时我得到的是:'property'name'不存在于'{}'类型'。 –

+1

@NikhilRadadiya如果你的对象中有未知的属性,你可以添加动态属性'product:{[key:string]:string}'这将允许你分配任何键(类型字符串) )。这被称为索引签名(https://basarat.gitbooks.io/typescript/docs/types/index-signatures.html) – LLai

+0

非常感谢你的男人,你拯救了很多人的生命,那索引结构就像一个魅力 –

2

首先我会简单地使用product: ProductInterface;,你甚至不需要初始化它。

然后,或许这将解决您的错误{{ product?. description }}

+0

使用'?'是什么意思? – celsomtrindade

+0

@celsomtrindade是安全的导航运算符(我相信它在其他语言中称为elvis运算符)http://www.concretepage.com/angular-2/angular-2-pipe-operator-and-safe-navigation-operator-例如。基本上角度不会查找描述字段,直到定义产品。没有它,你可能会得到一个无法读取未定义错误的属性描述。 – LLai

+0

所以@celsomtrindade你设法解决你的问题? – crash

0

你必须定义在OnInit方法的要求,你的控制器实现的OnInit接口和定义一个新的方法

ngOnInit(){ 
    this.product = this.request.getProduct(_id); // who is _id 
} 

假设getProduct()是http请求返回一个可观察到的

this.request.getProduct(_id).subscribe((data) => { 
    this.product=data; 
}); 
+0

这不是重点,我只是删除了不必要的代码,并忘记了这部分。请求功能正常工作。 – celsomtrindade

0

对我来说,它的工作组后,我的属性公共

所以,只要改变这个

export interface ProductInterface { 
    id: Number; 
    description: String; 
    title: String; 
} 

这个

export interface ProductInterface { 
    public id: Number; 
    public description: String; 
    public title: String; 
} 
相关问题