Angular 2如何将自定义提供程序注入服务?

时间:2016-04-29 11:38:42

标签: typescript angular

使用typescript,在main.ts中我有:

let myProvider = provide("message", { useValue: 'Hello' });

bootstrap(AppComponent, [
  myProvider
]);

如何将此注入我的服务(位于不同的文件中)? (请记住,我没有使用@Component注释。

2 个答案:

答案 0 :(得分:5)

I would use the @Inject decorator:

@Injectable()
export class SomeService {
  constructor(@Inject('message') message:string) {
  }
}

Don't forget to configure the service provider. For example when bootstrapping your application:

bootstrap(AppComponent, [ SomeService, myProvider ]);

答案 1 :(得分:2)

由于Dependency Injection doc不再提及字符串令牌,我建议使用OpaqueToken

应用程序/ config.ts

import {OpaqueToken, provide} from 'angular2/core';

export let MY_MESSAGE = new OpaqueToken('my-msg');
export let myProvider = provide(MY_MESSAGE, { useValue: 'Hello' });

应用程序/ app.component.ts

import {Component} from 'angular2/core';
import {myProvider} from './config';
import {MyService} from './MyService';

@Component({
  selector: 'my-app',
  providers: [myProvider, MyService],
  template: `{{msg}}`
})
export class AppComponent {
  constructor(private _myService:MyService) { 
    this.msg = this._myService.msg;
  }
} 

应用程序/ MyService.ts

import {Injectable, Inject} from 'angular2/core';
import {MY_MESSAGE} from './config';

@Injectable()
export class MyService {
  constructor(@Inject(MY_MESSAGE) private _message:String) { 
    this.msg = _message;
  }
}

Plunker