Reputation: 2397
I'm using Angular2 build 2.0.0-alpha.34 and I'm not sure why these two different pieces of code are giving me different results.
The only difference is using @Inject(TitleService) titleService
vs using titleService: TitleService
This correctly works (ES2015 way)
import {Inject, Component, View, bootstrap, NgFor} from 'angular2/angular2';
import {titleComponent} from './components/title';
import {TitleService} from './services/services';
// Annotation section
@Component({
selector: 'my-app'
})
@View({
templateUrl: './html/app.html',
directives: [titleComponent, NgFor]
})
// Component controller
class MyAppComponent {
titles: Array<Object>;
constructor(@Inject(TitleService) titleService) {
console.log(titleService)
this.titles = titleService.getTitles();
}
}
bootstrap(MyAppComponent,[TitleService]);
This doesn't work (TypeScript way), it doesn't ever make it to the console.log
call in constructor, but it doesn't throw an error
import {Inject, Component, View, bootstrap, NgFor} from 'angular2/angular2';
import {titleComponent} from './components/title';
import {TitleService} from './services/services';
// Annotation section
@Component({
selector: 'my-app'
})
@View({
templateUrl: './html/app.html',
directives: [titleComponent, NgFor]
})
// Component controller
class MyAppComponent {
titles: Array<Object>;
constructor(titleService: TitleService) {
console.log(titleService)
this.titles = titleService.getTitles();
}
}
bootstrap(MyAppComponent,[TitleService]);
If I'm using TypeScript's way to inject, do I need to do something else somewhere?
Upvotes: 0
Views: 793
Reputation: 773
You need to add it in the viewBindings of your Component annotation :
viewBindings: [TitleService]
Note that you only need to do it once, say in the Root component and every other component within the hierarchy will get it injecting from the root component, as if the component's injector can't resolve the dependency it goes up until it finds it. If you define one viewBindings you should have the same instance everywhere I believe.
edit: renaming of parameter in alpha 34.
Upvotes: 1
Reputation: 2397
I had TitleService defined in a JavaScript file, using an ES2015 class, I just needed to change it to a TypeScript file so it compiled correctly. Oops.
Upvotes: 0