0

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)

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Dan Soltesz
  • 898
  • 1
  • 9
  • 16
  • Why don't you make `Config` a class instead of an interface, then you don't need to use `OpaqueToken`? You can just use the `Config` class as a key for DI. `OpaqueToken` would be a good use case to inject a string into `Config` (for `appSetting`). – Günter Zöchbauer Apr 14 '16 at 05:55

1 Answers1

1

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 })
kemsky
  • 14,727
  • 3
  • 32
  • 51
  • that plunker isn't using the provider factory. I don't want Config to be a dependency in MyService, I just want a string to be a dependency. Hence the need for the factory. – Dan Soltesz Apr 13 '16 at 20:39
  • that did it..for my provider I had deps: [CONFIG] when it should be deps:[APP_CONFIG] – Dan Soltesz Apr 13 '16 at 21:10