Overriding Service Implementation
Learn about the various techniques for providing and configuring services in Angular to control the injection of dependencies and settings within components.
We'll cover the following...
We learned that a component could share its dependencies with its child components. Consider the FavoritesComponent
, where we used the slice
pipe to display a list of favorite products in its template. What if it needs to get data through a trimmed version of ProductsService
and not directly from the service instance of ProductListComponent
? We could create a new FavoritesService
that would extend the ProductsService
class and filter out data using the native slice
method of the array instead of the pipe. The favorites.service.ts
file would look like the following:
import { Injectable } from '@angular/core';import { ProductsService } from './products.service';import { Product } from './product';@Injectable({providedIn: 'root'})export class FavoritesService extends ProductsService {constructor() {super();}override getProducts(): Product[] {return super.getProducts().slice(1, 3);}}
Some things that should be pointed out in the preceding service are:
We use the
extends
keyword to indicate thatProductsService
is the base class ofFavoritesService
.The
constructor
calls thesuper
method to execute any business logic inside the base class constructor. ...