4

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.

2 Answers 2

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 ]); 
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.