The Power of InjectionToken Factory Functions in Angular

In this article, we are goanna talk about InjectionToken

InjectionToken: enable us to generate a global object or variable on module level.

The benefits of using the InjectionToken factory function are:

  • The provider is tree-shakeable, since we don’t need to inject it in our app module as we’d do with the useFactory provider.
  • Using inject() to request a provider is faster and more type-safe than providing an additional array of dependencies (which is the common usage of useFactory providers).
  • The provider has a single responsibility, and our components are injected only with the data they need.
  • It makes testing more straightforward because we don’t need to mock everything. We can return a mock value from the factory, and that’s all.

Here’s a simple real-world example

— let’s say you have a baseService, which which includes some basic functions like Get,Post,Delete…etc and we have a variable called BASE_URL like :

Then in the app.module.ts we need to provide this variable into providers and set it’s value.

Then in the app.component.ts we need to inject it .

Here’s another real-world example

we have a theme service

Then we need to inject it into out app.component

finally I hope this article was helpful and Thanks for your time.

--

--