Search⌘ K
AI Features

Overriding Service Implementation

Explore how to override Angular service implementations to manage dependencies effectively. This lesson covers extending services, using useClass and factory functions, and providing configuration objects with useValue and InjectionToken for flexible component design.

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:

TypeScript 4.9.5
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. ...