繁体   English   中英

构建时类型对象上不存在 Angular 4 属性

[英]Angular 4 Property does not exist on type Object on build

我正在使用 Angular 构建一个项目,我使用 angular-cli 启动了该项目,当我尝试运行ng build --prod我不断收到此错误:

类型对象上不存在属性“描述”

产生此错误的代码如下:

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> = {};

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

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

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

product: ProductInterface = {};

缺少界面的必填字段。 所以你可以删除初始化,离开

product: ProductInterface;

另外正如其他人所指出的,您不需要 Object<> 语法

从我的情况..

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

只需添加数据:订阅中的任何内容都可以正常工作。

this.request.getProduct(_id).subscribe((data: any) => {
   this.product=data;
});

当响应数据具有更多键值对时,这将很有帮助。 (因此创建界面很困难/耗时。)

但最好的做法总是使用接口;)

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

然后,这可能会解决您的错误{{ product?. description }} {{ product?. description }}

如果该属性是动态的(在编译时未知),则可以使用

someObject['someProperty']

而不是

someObject.someProperty

您必须在 OnInit 方法中定义请求,您的控制器实现 OnInit 接口并定义一个新方法

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

假设 getProduct() 是返回 observable 的 http 请求

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

在我的情况下,它在将我的属性设置为public 后工作

所以,只要改变这个

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

对此

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

当从服务器请求数据时,使用any而不是Object是安全的,因为我们不知道将从服务器返回什么。 所以,你不需要类型检查,即:

export class AppComponent {
    product: any;

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

如果您使用命令ng serve并构建成功。

可能,你在构建配置方面遇到了麻烦

也许你需要修改className.prod.tsclassName.ts

我的另一个答案有更多细节:

Angular - 如何修复“类型不存在属性”错误?

暂无
暂无

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

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