Value providers

A class provider creates class objects and fulfills the dependency, but at times we want to register a specific object/primitive with the DI provider instead. Value providers solve this use case.

Had we registered WorkoutHistoryTrackerService using this technique, the registration would have looked like this:

{provide: WorkoutHistoryTrackerService, useValue: new WorkoutHistoryTrackerService()};

With the value provider, we have the responsibility to provide an instance of a service/object/primitive to Angular DI.

With the value provider, since we are creating the dependency manually, we are also responsible for constructing any child dependencies if there are dependencies further down the lineage. Take the example of WorkoutHistoryTrackerService again. If WorkoutHistoryTrackerService has some dependencies, those too need to be fulfilled by manual injection:

{provide: WorkoutHistoryTrackerService, useValue: new WorkoutHistoryTrackerService(new LocalStorage())});

In the preceding example, we not only have to create an instance of WorkoutHistoryTrackerService, we also have to create an instance of the LocalStorage service. For a service with a complex dependency graph, setting up that service with a value provider becomes challenging.


Wherever possible, prefer class provider over value provider.

Value providers still come in handy in specific scenarios. For example, we can register a common app configuration using a value provider:

{provide: AppConfig, {useValue: {name:'Test App', gridSetting: {...} ...}}

Or register a mock dependency while unit testing:

{provide:WorkoutHistoryTrackerService, {useValue: new MockWorkoutHistoryTracker()}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.3.208