как вызвать класс функции javascript - PullRequest
0 голосов
/ 09 мая 2020

Я хотел создать класс с частными параметрами и функциями для доступа к нужным мне данным. Вы можете увидеть это:

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 ERROR TypeError: 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
}

Это моя услуга для получения данных

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();
  }
}

Ответы [ 2 ]

0 голосов
/ 09 мая 2020

После того, как Дэвид помог с комментариями, я понял, что мне нужно создать экземпляр данных, которые я получаю в http-клиенте.

Затем я изменил конструктор и свой клиент http get

  constructor(obj: any) {
    Object.assign(this, obj);
  }

и

private getDataFromApi(){
    this.http
      .get<Product[]>("../../assets/data.json").pipe()
      .toPromise()
      .then((data) => {
        const productList = data.map(product => new Product(product));
        this.dataApi.next(productList)});
  }
0 голосов
/ 09 мая 2020

У вас должен быть экземпляр класса Product перед доступом к его методам.

var newProduct = new Product();
newProduct.getName();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...