首页 > 解决方案 > 如何调用函数类javascript

问题描述

我想创建一个带有私有参数和函数的类来访问我想要的数据。你可以看到这个:

export class Product {
  private name: string;
  private type: string;
  private longDetail: string;
  private shortDetail: string;
  private stock: number;
  private price: number;
  private linkImage: string;
  private id: number;

  constructor(
    name: string,
    type: string,
    longDetail: string,
    shortDetail: string,
    stock: number,
    price: number,
    linkImage: string,
    id: number
  ) {
    this.name = name;
    this.type = type;
    this.longDetail = longDetail;
    this.shortDetail = shortDetail;
    this.stock = stock;
    this.price = price;
    this.linkImage = linkImage;
    this.id = id;
  }

  getName(): string {
    return this.name;
  }
  getType(): string {
    return this.type;
  }
  getLongDetail(): string {
    return this.longDetail;
  }
  getShortDetail(): string {
    return this.shortDetail;
  }
  getStock(): number {
    return this.stock;
  }
  getPrice(): number {
    return this.price;
  }
  getLinkImage(): string {
    return this.linkImage;
  }
  getId(): number {
    return this.id;
  }
}

当我想调用组件中的函数时,我被告知:

ProductListComponent.html:15 错误类型错误:newProduct.getName 不是函数

你有解决方案吗 ?非常感谢您提前!

编辑 :

这是前端点击后调用的代码

addProductBasket(newProduct: Product) {
  const newClientBasket = this.createNewClientBasketWithAdd(
    this.clientBasket.getValue(),
    newProduct
  )
  this.clientBasket.next(newClientBasket)
  console.log(newClientBasket)
}

private createNewClientBasketWithAdd(
  oldClientBasket: BasketProduct[],
  newProduct: Product
): BasketProduct[] {
  const found = oldClientBasket.find((product) => {
    if (product.getId() === newProduct.getId()) {
      product.addOneProduct()
    }
  })

  if (found === undefined) {
    console.log(newProduct.getName())
    oldClientBasket.push(
      new BasketProduct(
        newProduct.getName(),
        newProduct.getType(),
        newProduct.getLongDetail(),
        newProduct.getShortDetail(),
        newProduct.getStock(),
        newProduct.getPrice(),
        newProduct.getLinkImage(),
        newProduct.getId()
      )
    )
  }
  return oldClientBasket
}

获取数据是我的 apiservice

export class ApiService {
  private dataApi: BehaviorSubject<Product[]> = new BehaviorSubject<Product[]>([]);

  constructor(private http: HttpClient) {
    this.getDataFromApi();
  }
  private getDataFromApi(){
    this.http
      .get<Product[]>("../../assets/data.json")
      .toPromise()
      .then((data) => this.dataApi.next(data));
  }
  public getData():Observable<Product[]>{
    return this.dataApi.asObservable();
  }
}

标签: javascriptangularfunctionclassfrontend

解决方案


Product在访问其方法之前,您应该有一个类的实例。

var newProduct = new Product();
newProduct.getName();

推荐阅读