AngularService

Service
A class with a focused purpose.
Used for features that:
  • Are independent from any particular component
  • Provide shared data or logic across components
  • Encapsulate external interactions
Dependency Injection
A coding pattern in which a class receives the instances of objects it needs (called dependencies) from an external source rather than creating them itself.
Building and Registering a Service - at root application
filename: chapter-service.ts (dont forget - before service.ts)

import { IProduct } from "./product";
import { Injectable } from "@angular/core";
@Injectable({
  providedIn: 'root'
})
export class ProductService {
  getProducts(): IProduct[] {
    return [
      {
        productId: 1,
        productName: "Leaf Rake",
        productCode: "GDN-0011",
        releaseDate: "March 19, 2016",
        description: "Leaf rake with 48-inch wooden handle.",
        price: 19.95,
        starRating: 3.2,
        imageUrl:
          "https://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png"
      },
      
    ];
  }
}


Injecting the Service

We use the constructor to inject dependencies

product-list.component.ts
....
import { ProductService } from "./product-service";
@Component({ .... })..
constructor(private productService: ProductService) {
..... }