admin管理员组文章数量:1406924
Attempting to inject an object using an InjectionToken
.
In the AppModule
I have:
export const tokenConfigKey = new InjectionToken('config');
const tokenBasedConfig = {
provide: tokenConfigKey,
useValue: {
key: 'value'
}
}
And in the AppComponent
:
@Component({
selector: 'my-app',
template:`<h1>Hello Angular Lovers!</h1>`
})
export class AppComponent {
constructor(@Inject('config') config,
@Inject(tokenConfigKey) configByToken) {
}
}
This is a plete stacblitz example
Injection using the string key is passing, but injection with the token is failing. Any ideas why?
Article
Here's an article in case anyone wants to play with this
Attempting to inject an object using an InjectionToken
.
In the AppModule
I have:
export const tokenConfigKey = new InjectionToken('config');
const tokenBasedConfig = {
provide: tokenConfigKey,
useValue: {
key: 'value'
}
}
And in the AppComponent
:
@Component({
selector: 'my-app',
template:`<h1>Hello Angular Lovers!</h1>`
})
export class AppComponent {
constructor(@Inject('config') config,
@Inject(tokenConfigKey) configByToken) {
}
}
This is a plete stacblitz example
Injection using the string key is passing, but injection with the token is failing. Any ideas why?
Article
Here's an article in case anyone wants to play with this
Share edited Feb 16, 2019 at 0:08 Ole asked Feb 15, 2019 at 1:38 OleOle 47.5k70 gold badges238 silver badges445 bronze badges 1-
Are you using the same instance of the injection token? In other words, do you have something like...
import { tokenConfigKey } from '/path/to/app.module'
? – Pace Commented Feb 15, 2019 at 4:16
1 Answer
Reset to default 6A circular dependency issue could exist due to the fact that the AppModule
imports the AppComponent
and the AppComponent
imports the InjectionToken from the AppModule
.
Moving token to separate resolvs the issue:
token.ts
import { InjectionToken } from '@angular/core';
export const BASE_URL = new InjectionToken<string>('BaseUrl');
app.module.ts
@NgModule({
providers: [{ provide: BASE_URL, useValue: { key: 'http://localhost' } }],
app.ponent.ts
constructor(@Inject(BASE_URL) configByToken) {
console.log(configByToken);
}
本文标签: javascriptInjection using an InjectionTokenStack Overflow
版权声明:本文标题:javascript - Injection using an InjectionToken? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745056393a2639962.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论