angularangular2-injection

Angular 2: How to inject simple types into your service


I have a basic service that has a single string parameter

import {Injectable} from 'angular2/core';
@Injectable()
export class MyService  {
    constructor(someValue: string) {
    }
}

If I remove the string param from the constructor the service will inject fine but I can't seem to figure out how to get a simple string to get injected.

I have defined a config to store application settings

import {OpaqueToken} from 'angular2/core';

export let APP_CONFIG = new OpaqueToken('app.config');

export interface Config {
appSetting: string,

}

export const CONFIG: Config = {
appSetting: "my application nsetting"
};

I defined a factory for MyService

import {provide}     from 'angular2/core';
import {MyService} from './my.service';
import {Config, CONFIG}    from './app.config';


let myServiceFactory = (config: Config) => {
return new MyService(config.appSetting);
}

export let myServiceProvider =
provide(MyService, {
    useFactory: myServiceFactory,
    deps: [CONFIG]
});

in my bootstrapping I register the provider

import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
import {provide} from 'angular2/core';
import {APP_CONFIG, CONFIG}    from './app.config';
import {myServiceProvider} from './my.service.provider';

bootstrap(AppComponent,
[provide(APP_CONFIG, { useValue: CONFIG }),
 myServiceProvider   
]);

in my app component I try to inject myService

import {Component} from 'angular2/core';
import {MyService} from './my.service';
@Component({
selector: 'my-app',
template: '<h1>Angular 2 is running</h1>'
providers: [
    MyService
]
})
export class AppComponent {

constructor(private _myService: MyService) {
}
}

the application never starts up and I get this error

0x800a139e - JavaScript runtime error: Uncaught (in promise): No provider for String! (AppComponent -> MyService -> String)


Solution

  • Check this plank, i've tried to fix your sample. You could inject string values in the same way as Config object using OpaqueTokens.

    The most important parts:

    deps: [APP_CONFIG]
    provide(APP_CONFIG, { useValue: CONFIG })