我想在我的服务中注入一个带有我的配置参数的类。
我在下面做了示例代码,但它不起作用:
import { Config } from '../app.constants';
console.log(Config); // here i can access to my properties of config
@Injectable()
export class MyService {
protected config: Config;
constructor(protected _http: Http, @Inject(Config) _configuration: Config) {
console.log(this.config); // undefined
console.log(_configuration); // undefined
}
我想我并没有理解角度2的范围和注入过程。 如何在我的服务MyService中访问我的类Config?
编辑:
这是我的模块
import { NgModule } from '@angular/core';
import { MyService } from './my.service';
import { Config } from '../app.constants';
@NgModule({
imports: [
],
declarations: [
MyService
],
exports: [
MyService
],
providers: [
MyService,
Config
]
})
export default class MyModule {}
这是我的配置:
import { Injectable } from '@angular/core';
@Injectable()
export class Config {
public Port: number = 1234;
public Server: string = "http://my-server.com";
}
不会直接调用MyService服务,但我将其扩展为:
@Injectable() 导出类TestService扩展MyService { ... }
是这样导入的:
import { TestService } from '../service/test.service';
//some modules are from ng2-admin, we can ignore them
@NgModule({
imports: [
CommonModule,
NgaModule,
TestRouting
],
declarations: [
TestComponent,
HoverTable
],
exports: [
TestComponent,
HoverTable
],
providers: [
TestService
]
})
export default class TestModule {}
最后是我的组件
@Component({
selector: 'test-list',
template: require('./test.html')
})
export class TestComponent {
constructor(protected service: TestService) {
//console.log(service);
}
答案 0 :(得分:3)
export class MyService {
protected config: Config;
constructor(protected _http: Http, @Inject(Config) _configuration: Config) {
console.log(this.config); // undefined
console.log(_configuration); // undefined
}
}
您永远不会在任何地方初始化配置字段,因此它未定义。你所需要的只是
export class MyService {
protected config: Config;
constructor(protected _http: Http, _configuration: Config) {
this.config = _configuration;
}
}
或者只是
export class MyService {
protected config: Config;
constructor(protected _http: Http, protected config: Config) {
}
}
由于MyService是一个服务,它必须添加到模块的提供者,而不是声明(用于组件,管道和指令):
@NgModule({
providers: [
MuleService,
Config,
MyService
]
})
如果您只想将TestService用作服务而不是MyService,请确保TestService具有一个构造函数,该构造函数也接受必须注入的所有参数:
constructor(http: Http, config: Config) {
super(http, config);
}