...

/

Overriding Service Implementation

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 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:

Press + to interact
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 that ProductsService is the base class of FavoritesService.

  • The constructor calls the super method to execute any business logic inside the base class constructor. ...