Using the inject() function – Angular Services and the Singleton Pattern

The inject() function allows you to use the same dependency injection feature but in a simpler way.
Let’s refactor our component’s code:

import { Component,
inject
} from ‘@angular/core’;
import { ExerciseSet } from ‘../interfaces/exercise-set’;
import { ExerciseSetsService } from ‘../services/exercise-sets.service’;
.
.
.
export class DiaryComponent {
private exerciseSetsService = inject(ExerciseSetsService);
exerciseList = this.exerciseSetsService.getInitialList();
.
.
.
}

Here we remove the constructor declaration for the dependency injection and directly declare the exerciseSetsService service. For the creation of the object, we use the inject function.
A point of note is that we are using the inject function of the @angular/core module and not the function present in the @angular/core/testing module, which will be used for another purpose.
This method, in addition to being simpler and clearer (the service is being injected by the function), allows the simplification of development, if it is necessary to use inheritance for a specific component. Remembering that good practice says we should prefer composition over inheritance, but especially in libraries, this feature can be interesting.
A point of note for the use of the inject function is that it can only be used in the component’s construction phase, that is, in the declaration of the method’s property or in the class’s constructor method.
Any use in another context will generate the following compilation error:

inject() must be called from an injection context
such as a constructor, a factory function, a field initializer,
or a function used with runInInjectionContext.

Let’s now delve into another aspect of Angular services, which is the use of the singleton design pattern, and how we can use this capability for communication between components.

Write a Comment

Your email address will not be published. Required fields are marked *