Understanding the dependency injection pattern
In object-oriented software development, it is good practice to prioritize composition over inheritance, meaning that a class should be composed of other classes (preferably interfaces).
In our previous example, we can see that the service
class comprises the DiaryComponent
component. Another way to use this service would be as follows:
. . . export class DiaryComponent { private exerciseSetsService: ExerciseSetsService; exerciseList: ExerciseSetList; constructor() { this.exerciseSetsService = new ExerciseSetsService(); this.exerciseList = this.exerciseSetsService.getInitialList(); } . . . }
Here we modify our code, leaving the creation of the service class object expressly in the component’s constructor method. Running our code again, we can see that the interface remains the same.
This approach, although functional, has some...