【发布时间】:2017-05-11 02:45:25
【问题描述】:
我想用我的配置参数在我的服务中注入一个类。
我做了下面的示例代码,但它不起作用:
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
}
我想我没有理解 Angular 2 的作用域和注入过程。 如何在我的服务 MyService 中访问我的类配置?
编辑:
这是我的模块
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);
}
【问题讨论】:
-
你试过
console.log( this. _configuration )吗? -
我没有影响到我的类中的 _configuration,它只是我的构造函数的一个本地属性。
-
@estus 我用大量数据编辑了我的问题
标签: angular typescript