Example of InjectionToken With Non-class dependencies

Not all dependencies are classes. Sometimes you want to inject a string, function, or object. Apps often define configuration objects with lots of small facts, like the title of the application or the address of a web API endpoint. These configuration objects aren’t always instances of a class. They can be object literals, as shown in the following example.

In this application there 2 module DashboardModule, HeroDetailModule both modules use the same service but with different API URL

both modules can be configured with InjectionToken.

Dashboard module directory

dashboard folder index.ts file created

injection token type can be anything in this module <string> used, the unique token is pass as a parameter.


In module providers defined with useValue


now dashboard component API_URL can be used as a service. In constructor @Optional() @Inject(API_URL) config is used in the component. when this component loaded then config variable will contain ‘https://rickandmortyapi.com/api/character’ for the Dashboard component only.


here injectionToken type is Object and ‘someTokenEpisode’ value pass as a parameter.


here the same approach used to define providers. but useValue is passed as the type of object.

Final Output


In the beginning, the dashboard module loaded so in the dashboard.component.ts service API_URL value is ‘https://rickandmortyapi.com/api/character'. and after clicking on hero card hero-details.module loaded then as per configuration value of API_URL is changed with object { apiEndpoint: ‘https://rickandmortyapi.com/api/location', title: ‘Location of character’}.

Claps help other people finding it and encourage me to write more posts