, Angular, , .
:
export const APP_CONFIG = new InjectionToken<string>('AppConfig');
, . . , .
export interface AppConfig {
name: string;
baseUrl: string;
}
. forRoot(), . , , , ( ).
import { Injectable, NgModule, SkipSelf, Optional } from '@angular/core';
@NgModule({
providers: [
YourServiceClass
]
})
export class ServiceModule {
public static forRoot(config: AppConfig) {
return {
ngModule: ServiceModule,
providers: [
{provide: APP_CONFIG, useValue: config}
]
};
}
public constructor(@Optional() @SkipSelf() parentModule: ServiceModule) {
if(parentModule) {
throw new Error('ServiceModule has already been imported.');
}
}
}
.
@Injectable()
export class YourServiceClass {
public constructor(@Inject(APP_CONFIG) config: AppConfig) {
}
}
, forRoot .
@NgModule({
imports: [
ServiceModule.forRoot({
name: 'FooBar',
baseUrl: 'http://www.example.com/'
})
]
})
export class MainModule {}
, , forRoot . APP_CONFIG, . , , forRoot, , , .
, ServiceModule APP_CONFIG undefined. . ServiceModule , . , , .
, , , ServiceModule. , . . , , , .