[英]ngFor Property 'id' does not exist on type 'Object'
Im trying to learn angular and Im following a code tutorial and as far as I can tell my code matches the instructors but it's not working.我正在尝试学习 angular 并且我正在遵循代码教程,据我所知,我的代码与讲师匹配,但它不起作用。
I have the following code and it fails to compile saying the objects dont exist.我有以下代码,它无法编译说对象不存在。 what am i missing?我错过了什么?
import { ThrowStmt } from '@angular/compiler';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
products:Object[];
constructor() {
this.products = [
{
id: "1",
name:"Mac Book Pro"
},
{
id: "2",
name:"iPhone"
}
];
}
public getProducts(){
return this.products;
}
ngOnInit(): void {
}
}
Product Details:
<div *ngFor="let product of products">
<h1>{{product.name}}</h1>
<h1>{{product.id}}</h1>
</div>
it prints out [[object Object]] twice if i remove the.name and.id, but as it stands i get the following errors.如果我删除.name和.id,它会打印两次[[object Object]],但就目前而言,我得到以下错误。
4 <h1>{{product.name}}{{product.id}}</h1>
~~~~
src/app/product/product.component.ts:6:16
6 templateUrl: './product.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component ProductComponent.
Error: src/app/product/product.component.html:4:35 - error TS2339: Property 'id' does not exist on type 'Object'.
4 <h1>{{product.name}}{{product.id}}</h1>
~~
SOLVED I have solved the issue by changing from Object[] to any[].已解决我通过从 Object[] 更改为 any[] 解决了这个问题。
products:any[];产品:任何[];
this solved the issue.这解决了这个问题。
You have to specify products
type as the array with strongly typed class/interface instead of Object[]
;您必须将products
类型指定为具有强类型类/接口而不是Object[]
的数组;
product.model.ts产品.model.ts
export interface Product {
id: string;
name: string;
}
product.component.ts product.component.ts
import { Product } from '../models/product.model';
products: Product[];
Sample Solution 1 on StackBlitz StackBlitz 上的示例解决方案 1
Alternative, change the text interpolation as below if you prefer products
as Object[]
type.或者,如果您更喜欢将products
作为Object[]
类型,请按如下方式更改文本插值。
<div *ngFor="let product of products">
<h1>{{product["name"]}}</h1>
<h1>{{product["id"]}}</h1>
</div>
Try using ?
尝试使用?
operator, like this:运算符,如下所示:
<div *ngFor="let product of products">
<h1>{{product?.name}}</h1>
<h1>{{product?.id}}</h1>
</div>
Your current code will break if any product is missing name
or id
property.如果任何产品缺少name
或id
属性,您当前的代码将中断。
The issue was using the type Object[] Swapping to any[] solved the issue.问题是使用类型 Object[] 交换到 any[] 解决了这个问题。
Change products:Object[];更改产品:Object[]; to products:any[];到产品:任何[]; Ie the type should be any instead of Object.即类型应该是any 而不是Object。 this is a general angular bug.这是一个一般的 angular 错误。 Hope they resolve it.希望他们解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.