williamsandonz
williamsandonz

Reputation: 16420

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

Using typescript, In main.ts I have:

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.

Upvotes: 4

Views: 1828

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364677

Since the Dependency Injection doc no longer mentions string tokens, I recommend using an OpaqueToken:

app/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

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

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

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202146

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

Upvotes: 5

Related Questions