Reputation: 633
I don't understand why the following does not work. If I use a literal string for assigning APP_BASE_HREF it works fine.
main.ts
export function main(baseHref: string) {
platformBrowserDynamic([
{ provide: MY_BASE_HREF, useValue: baseHref },
]).bootstrapModule(AppModule);
}
app.module.ts
export const MY_BASE_HREF = new InjectionToken<string>('BaseHref')
@NgModule({
...
providers: [{ provide: APP_BASE_HREF, useValue: MY_BASE_HREF }],
...
})
Here Is The Important Part of the Console Error
Unhandled Promise rejection: url.replace is not a function ; Zone: <root> ; Task: Promise.then ; Value: TypeError: url.replace is not a function
at _stripIndexHtml (node_modules/@angular/common/bundles/common.umd.js:439)
at new Location (node_modules/@angular/common/bundles/common.umd.js:278)
Can I not use an InjectionToken to define another InjectionToken?
Upvotes: 4
Views: 2267
Reputation: 4209
For those who are looking how to inject InjectionToken inside another InjectionToken factory
.
There is another way as described in this article.
import { InjectionToken, inject } from '@angular/core';
export const ONE = new InjectionToken<string>('ONE', {
providedIn: 'root',
factory: () => 'value'
});
export const TWO = new InjectionToken<string>('TWO', {
providedIn: 'root',
factory: () => {
const one = inject(ONE); // this is the injection
return one + ' received from ONE';
}
});
Upvotes: 0
Reputation: 657108
As far as I remember this should do what you want
providers: [{ provide: APP_BASE_HREF, useFactory: (url) => url, deps: [MY_BASE_HREF]}],
Upvotes: 5