Reputation: 4547
I'm following the angular docs for Dependency Injection and tried to duplicate the section on dependency injection tokens.
define OpaqueToken in separate JS module
// app-config.ts
import { OpaqueToken } from '@angular/core';
export let APP_CONFIG = new OpaqueToken('app.config');
// use class instead of interface
export interface AppConfig {
apiEndpoint: string;
title: string;
}
export const HERO_DI_CONFIG: AppConfig = {
apiEndpoint: 'api.heroes.com',
title: 'Dependency Injection'
};
import APP_CONFIG
& ALSO define APP_CONFIG2
// app-modules.ts
import { APP_CONFIG, HERO_DI_CONFIG } from './app-config.ts';
export let APP_CONFIG2 = new OpaqueToken('app.config2');
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
providers: [
{provide: APP_CONFIG, useValue: HERO_DI_CONFIG},
{provide: APP_CONFIG2, useValue: HERO_DI_CONFIG},
],
bootstrap: [ App ]
})
and inject
into a Component constructor
// app.ts
import { APP_CONFIG, AppConfig } from './app-config.ts'
import { APP_CONFIG2 } from './app-module.ts'
export class App {
constructor(
@Inject(APP_CONFIG) public opaqueToken: AppConfig
@Inject(APP_CONFIG2) public opaqueToken2: any
) {
this.name = 'Angular2'
this.local = LOCAL_STRING
}
}
APP_CONFIG
which is defined in an external module is injected correctly, but APP_CONFIG2
, which was defined in the same module as the provide
throws an error. Why is that?
VM466 zone.js:323Error: (SystemJS) Error: Can't resolve all parameters for App: (Token_app_config, ?,
Here's a plunkr: http://plnkr.co/edit/5TkKAozC2vjXI9DfjMLg?p=preview
Upvotes: 3
Views: 711
Reputation: 914
This is not an issue with Angular, but with circular dependencies between es6 modules.
In your example, app.ts
imports APP_CONFIG
from app.module.ts
and app.module.ts
imports App
from app.ts
.
This creates a circular dependency which cannot be resolved.
Upvotes: 1
Reputation: 13558
To make it work you have to export APP_CONFIG2
from app-config.ts
and import it from app-config.ts
in your app-modules.ts
and app.ts
file :
// app-config.ts
import { OpaqueToken } from '@angular/core';
export let APP_CONFIG = new OpaqueToken('app.config');
export let APP_CONFIG2 = new OpaqueToken('app.config');
Upvotes: 0