Я пишу фронтенд для pet проекта на Angular, но мало знаком с ним. Я получаю несколько json-ов, после чего кладу их в поля класса app.component, представляющие собой массивы доменных объектов. Данный процесс проходит хорошо, json-ы успешно кладутся в поля, это происходит в конструкторе. Однако затем я хочу спарсить json-ы по значению ключей в новый массив типа интерфейс ProductCard, описанный тут же в app.component для дальнейшего использования в компоненте product-card.component (я так уже делал с интерфейсом Icon и компонентом icon.component, однако там я не парсил значения из json, а вводил вручную, т.к. количество элементов было фиксированным (всего 3). Массив productCards я хочу заполнить по прописанному условию в методе fillProductCards, однако я не знаю, где я могу вызвать данный метод? Заполнение данного массива мне нужно заранее, вызов через html отрабатывает нормально, но мне нужно, чтобы массив заполнялся при нажатии на button или что-то в этом духе(при вызове в div метод вызвается миллион раз). Где можно вызвать данный метод? Код прилагаю.
app.component.ts:
import {Component} from '@angular/core';
import {Category} from "./domain/category";
import {HttpClient} from "@angular/common/http";
import {Product} from "./domain/product";
import {Offer} from "./domain/offer";
export interface Icon {
width: number
height: number
src: string
alt: string
}
export interface ProductCard {
productId: bigint
offerId: bigint
price: number
priceOverride: number
article: string
productName: string
imageUrl: string
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
maleCategory!: Category[];
femaleCategory!: Category[];
products: Product[] = [];
offers: Offer[] = [];
maleMenuShow: boolean = false;
femaleMenuShow: boolean = false;
constructor(private http: HttpClient) {
this.http.get<Category[]>('http://localhost:8080/rest/categories/MALE').subscribe(result => {
this.maleCategory = result;
});
this.http.get<Category[]>('http://localhost:8080/rest/categories/FEMALE').subscribe(result => {
this.femaleCategory = result;
});
this.http.get<Product[]>('http://localhost:8080/rest/products').subscribe(result => {
this.products = result;
console.log(this.products)
});
this.http.get<Offer[]>('http://localhost:8080/rest/offers').subscribe(result => {
this.offers = result;
});
}
showFemaleMenu() {
this.femaleMenuShow = true;
console.log('success')
}
hideFemaleMenu(): void {
this.femaleMenuShow = false;
}
showMaleMenu() {
this.maleMenuShow = true;
}
hideMaleMenu(): void {
this.maleMenuShow = false;
}
getProductById(productId: bigint): Product {
let currentProduct = new Product();
for (let i = 0; i < this.products.length; i++) {
if (this.products[i].id == productId) {
currentProduct = this.products[i]
}
}
return currentProduct;
}
makeBig(number: number) {
return BigInt(number)
}
icons: Icon[] = [
{width: 30, height: 30, src: 'assets/img/icons/search.png', alt: 'Поиск'},
{width: 30, height: 30, src: 'assets/img/icons/user.png', alt: 'Личный кабинет'},
{width: 30, height: 30, src: 'assets/img/icons/cart.png', alt: 'Корзина'}
]
productCards: ProductCard[] = [];
currentProductCard!: ProductCard;
currentProduct: Product = new Product();
fillProductCards() {
for (let i = 0; i < this.offers.length; i++) {
this.currentProduct = this.getProductById(this.offers[i].productId);
this.currentProductCard = {
productId: this.currentProduct.id,
offerId: this.offers[i].id,
price: this.offers[i].price,
priceOverride: this.offers[i].priceOverride,
article: this.currentProduct.article,
productName: this.currentProduct.productName,
imageUrl: this.currentProduct.imageUrl
}
this.productCards.push(this.currentProductCard)
}
}
}
icon.component.ts:
import {Component, Input, OnInit} from '@angular/core';
import {Icon} from "../../app.component";
@Component({
selector: 'app-icon',
templateUrl: './icon.component.html',
styleUrls: ['./icon.component.scss']
})
export class IconComponent implements OnInit {
@Input() icon!: Icon
@Input() index!: number
width!: number
height!: number
src!: string
alt!: string
opacity: number = 0.5
ngOnInit(): void {
}
}
product-card.component.ts
import {Component, Input, OnInit} from '@angular/core';
import {ProductCard} from "../../app.component";
@Component({
selector: 'app-product-card',
templateUrl: './product-card.component.html',
styleUrls: ['./product-card.component.scss']
})
export class ProductCardComponent implements OnInit {
@Input() productCard!: ProductCard
@Input() index!: number
productId!: bigint
offerId!: bigint
price!: number
priceOverride!: number
article!: string
productName!: string
imageUrl!: string
ngOnInit(): void {
}
}