You are on page 1of 3

Atelier de développement 2Ginfo

Solutionnaire

Exercice 2 :

Créer un service qui permet d’afficher une liste de produit en cliquant sur un bouton.

Sol :

Créer une nouvelle classe product :

export class Product {

constructor(productID:number, name: string , price:number) {


this.productID=productID;
this.name=name;
this.price=price;
}

productID:number ;
name: string ;
price:number;

Créer un service Product qui retourne la liste de service

import {Product} from './product'


Atelier de développement 2Ginfo

export class ProductService{

public getProducts() {

let products:Product[];

products=[
new Product(1,'Memory Card',500),
new Product(1,'Pen Drive',750),
new Product(1,'Power Bank',100)
]

return products;
}
}

Invocation du service dans le composant :

import { Component } from '@angular/core';

import { ProductService } from './product.service';


import { Product } from './product';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})

export class AppComponent


{

products:Product[];|undefined ;
productService;

constructor(){
this.productService=new ProductService();
}

getProducts() {

this.products=this.productService.getProducts();
}

Création d’un objet product et invocation de la liste de produits à partir du service.

Contenu de app.component.html
Atelier de développement 2Ginfo

<div class="container">
<h1 class="heading"><strong>Services </strong>Demo</h1>

<button type="button" (click)="getProducts()">Get Products</button>

<div class='table-responsive'>
<table class='table'>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let product of products;">
<td>{{product.productID}}</td>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
</tr>
</tbody>
</table>
</div>

</div>

You might also like