[英]Property 'filter' does not exist on type 'Object'. When trying to filter response
[英]ngFor Property 'id' does not exist on type 'Object'
我正在尝试学习 angular 并且我正在遵循代码教程,据我所知,我的代码与讲师匹配,但它不起作用。
我有以下代码,它无法编译说对象不存在。 我错过了什么?
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>
如果我删除.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>
~~
已解决我通过从 Object[] 更改为 any[] 解决了这个问题。
产品:任何[];
这解决了这个问题。
您必须将products
类型指定为具有强类型类/接口而不是Object[]
的数组;
产品.model.ts
export interface Product {
id: string;
name: string;
}
product.component.ts
import { Product } from '../models/product.model';
products: Product[];
或者,如果您更喜欢将products
作为Object[]
类型,请按如下方式更改文本插值。
<div *ngFor="let product of products">
<h1>{{product["name"]}}</h1>
<h1>{{product["id"]}}</h1>
</div>
尝试使用?
运算符,如下所示:
<div *ngFor="let product of products">
<h1>{{product?.name}}</h1>
<h1>{{product?.id}}</h1>
</div>
如果任何产品缺少name
或id
属性,您当前的代码将中断。
问题是使用类型 Object[] 交换到 any[] 解决了这个问题。
更改产品:Object[]; 到产品:任何[]; 即类型应该是any 而不是Object。 这是一个一般的 angular 错误。 希望他们解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.