В этой статье мы отобразим отдельную деталь продукта в компоненте. Прежде всего, нам нужно перейти к разделу компонентов чтения и создать следующие свойства класса.
productID: any; //Getting Product id from URL productData: any; //Getting Product details
Затем введите службу CURD, маршрутизатор и ActivatedRoute, используя внедрение зависимостей в компонент представления.
constructor( private crudService: CrudService, private router: Router, private actRoute: ActivatedRoute) { }
создать метод для загрузки сведений о продукте здесь Я даю блок кода этого метода
loadProductDetails(productID){ this.crudService.getProductDetails(productID).subscribe(product => { this.productData = product; }); }
Я получил доступ к службе CRUD и получил здесь подробную информацию о продукте. Я сохранил информацию о продукте в свойстве productData.
this.productData = product;
Затем я хочу получить идентификатор продукта из URL-адреса. Итак, здесь я использую функцию ActivatedRoute.
this. productID = this.actRoute.snapshot.params['id'];
этот код получил идентификатор продукта из URL-адреса.
затем я внедрил методы loadProductDetails в метод ngOnInit.
ngOnInit() { this. productID = this.actRoute.snapshot.params['id']; this.loadProductDetails(this.productID); }
вот последний блок кода файла read.component.ts.
import { Component, OnInit } from '@angular/core'; import {CrudService} from "../../services/crud.service"; import {Router, ActivatedRoute} from "@angular/router"; @Component({ selector: 'app-read', templateUrl: './read.component.html', styleUrls: ['./read.component.scss'] }) export class ReadComponent implements OnInit { productID: any; productData: any; constructor( private crudService: CrudService, private router: Router, private actRoute: ActivatedRoute) { } ngOnInit() { this. productID = this.actRoute.snapshot.params['id']; this.loadProductDetails(this.productID); } loadProductDetails(productID){ this.crudService.getProductDetails(productID).subscribe(product => { this.productData = product; }); } navigation(link){ this.router.navigate([link]); } }
Теперь мы перейдем к разделу шаблона компонента и отобразим подробную информацию о продукте, используя метод интерполяции строк.
<div class="container-fluid"> <div class="row"> <div class="col-12 col-lg-12 col-md-12 sol-sm-12"> <table class="table table-striped"> <tr> <td>Name</td> <td>{{productData['p_name']}}</td> </tr> <tr> <td>Description</td> <td>{{productData['p_description']}}</td> </tr> <tr> <td>Price</td> <td>{{productData['p_price']}}</td> </tr> </table> <br> <button class="btn btn-warning" (click)="navigation('')">Go Back</button> </div> </div> </div>
в следующей статье я объясню, как создать новый продукт.