Search code examples
angularangular7angular8angular-dependency-injection

Transitively inject injection token into a service defined in library, used within an angular application


I've created an angular library, say library1, which defines and exposes a service APIService. The APIService has a constructor argument (URL: string), which is injected with an Injection token defined as,

const URL_TOKEN = new InjectionToken<string>('API_BASE_URL');

I use this library1 in yet another library, say library2, i.e. I inject the APIService within a component called LoginComponent.

Now I have a full-fledged angular application, and I use the LoginComponent from library2, and I wish to provide the value of URL from the application.

I wonder if there is a way to achieve this. I'm also not sure how to expose URL_TOKEN from library1 all the way to the angular application in a nice way.

Update

When I try to inject API_BASE_URL as,

providers: [ {provide: new InjectionToken<string>('API_BASE_URL'), useValue: 'http://endpoint'} ]

I get an exception in the browser: ERROR NullInjectorError: StaticInjectorError(AppModule)[InjectionToken API_BASE_URL]:


Solution

  • I ended up exporting URL_TOKEN all the way. After going through bunch of resources (stack overflow questions, github posts, angular docs etc.), that seems to be the right way to do it.