【问题标题】:Property does not exist on type 'Class' when using filter in Angular在 Angular 中使用过滤器时,“类”类型上不存在属性
【发布时间】:2021-04-15 10:30:57
【问题描述】:

我在 Angular 管道中使用 array.filter,并导入了我创建的类:

import { Pipe, PipeTransform } from '@angular/core';
import Product from '../models/Product';

@Pipe({
  name: 'products'
})
export class ProductsPipe implements PipeTransform {

  transform(products: Product[], valueToSearch: string): any {
    return products.filter( product => product.name);
  }

}

由于某种原因,我收到了这个错误:Property 'name' does not exist on type 'Product',这很有趣,因为它绝对存在于 Product 类型上。

这是第二次使用过滤器,有人可以帮忙吗?

模型:


export default class Product {
    public constructor(
        ID: number,
        name: string,
        category: string,
        price: number,
        imageURL: string
    ) {};
}

我设法弄明白了,我的模型没有他的“公共”属性。

【问题讨论】:

  • 为“../models/Product”添加代码;
  • 分享你的模型

标签: angular typescript types


【解决方案1】:

我设法弄明白了,我的模型没有他的“公共”属性。 现在看起来像这样:

export default class Product {
    public constructor(
        public ID: number,
        public name: string,
        public category: string,
        public price: number,
        public imageURL: string
    ) {};
}

【讨论】:

    【解决方案2】:

    很高兴您解决了这个问题,另一种解决方案是使用界面。这将是合适的,因为您的类似乎没有任何方法,因此接口适合键入

    export interface Product {
       ID: number,
       name: string,
       category: string,
       price: number,
       imageURL: string
    }
    

    并像import { Product } from '..models/Product'一样导入它

    【讨论】:

      猜你喜欢
      • 2020-02-15
      • 2019-04-24
      • 2017-05-23
      • 1970-01-01
      • 2021-08-11
      • 2019-08-27
      • 1970-01-01
      • 2018-12-11
      • 2018-07-12
      相关资源
      最近更新 更多