Creating and Using service

// file (acting as a local service(json data) ) //================================ //FILE: product.service.ts //================================ //to inject service import { Injectable } from '@angular/core'; //to import interface (strored in some other file) import { IProduct } from './product'; //export statement (so that this service can be imported where it is required) export class ProductService { // method/function that returns data (array of objects(contaning data chunks)) getProducts(): IProduct[] { // apply interface for strong typing //return or send this data/service return [ { "productId": 1, "productName": "Leaf Rakee", "productCode": "GDN-0011", "releaseDate": "March 19, 2016", "description": "Leaf rake with 48-inch wooden handle.", "price": 19.95, "starRating": 3.2, "imageUrl": "http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png" }, { ... }, { ... } ] } } // file where service is being called //================================ //FILE: product-list.component.ts //================================ export class ProductListComponent implements OnInit { pateTitle: 'Acme Product List' products: IProduct[]; // why constructor is required // why _productService is required // why 'private' is required constructor(private _productService: ProductService) {} // assign or pass on service-data to variable 'products' ngOnInit(): void { this.products = this._productService.getProducts(); } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.