Example of InjectionToken With Non-class dependencies

Rajratna maitry
3 min readApr 22, 2020

--

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

in InjectionToken ‘someTokenCharacter’ must be unique.

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

dashboard.component.ts

In module providers defined with useValue

dashboard.componet.ts

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.

hero-detail/index.ts

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

hero-detail.module.ts

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

Final Output

summary

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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response