繁体   English   中英

Angular 2将类注入服务

[英]Angular 2 inject a class into a service

我想用我的配置参数在我的服务中注入一个类。

我做了下面的示例代码,但是没有用:

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中访问类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);

   }
export class MyService {

  protected config: Config;

  constructor(protected _http: Http, @Inject(Config) _configuration: Config) {
    console.log(this.config); // undefined
    console.log(_configuration); // undefined
  }
}

您永远不会在任何地方初始化config字段,因此它是未定义的。 所有你需要的是

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM