简体   繁体   English

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

[英]Angular 2 How can I inject a custom provider into a service?

Using typescript, In main.ts I have: 使用typescript,在main.ts我有:

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

bootstrap(AppComponent, [
  myProvider
]);

How can I inject this into my service (which is in a different file)? 如何将此注入我的服务(在不同的文件中)? (Keep in mind I'm not using the @Component annotation. (请记住,我没有使用@Component注释。

I would use the @Inject decorator: 我会使用@Inject装饰器:

@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 ]);

Since the Dependency Injection doc no longer mentions string tokens, I recommend using an OpaqueToken : 由于Dependency Injection文档不再提及字符串标记,我建议使用OpaqueToken

app/config.ts 应用程序/ 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/app.component.ts 应用程序/ 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;
  }
} 

app/MyService.ts 应用程序/ 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 Plunker

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

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