Это мой HTML:
-
19.22 2
>
Компонент служб:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Product } from '../common/product';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ProductService {
private baseUrl = 'http://localhost:8080/api/products';
constructor(private httpClient: HttpClient) { }
getProductList(theCategoryId: number): Observable
{
//need to build URL based on category id
const searchUrl = `${this.baseUrl}/search/findByCategoryId?id=${theCategoryId}`;
return this.httpClient.get(searchUrl).pipe(
map(response => response._embedded.products)
);
}
}
interface GetResponse{
_embedded: {
products: Product[];
}
}
Компонент списка продуктов:
import { Component, OnInit } from '@angular/core';
import { ProductService } from '../../services/product.service';
import { Product } from '../../common/product';
import { CommonModule } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product-list',
imports: [CommonModule],
templateUrl: './product-list-grid.component.html',
styleUrl: './product-list.component.css'
})
export class ProductListComponent implements OnInit{
products: Product[] = [];
currentCategoryId: number = 1;
constructor(private productService: ProductService,
private route: ActivatedRoute) { }
ngOnInit() {
this.route.paramMap.subscribe(() => {
this.listProducts();
});
}
listProducts() {
// check if "id" parameter is available
const hasCategoryId: boolean = this.route.snapshot.paramMap.has('id');
if (hasCategoryId) {
// get the "id" param string. convert string to a number using the "+" symbol
this.currentCategoryId = +this.route.snapshot.paramMap.get('id')!;
}
else {
// not category id available ... default to category id 1
this.currentCategoryId = 1;
}
// now get the products for the given category id
this.productService.getProductList(this.currentCategoryId).subscribe(
data => {
this.products = data;
}
)
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... ular-proje