Rob Snider
Rob Snider

Reputation: 33

Angular 2 Dependency Injection

I have read several articles on dependency injection and cannot seem to get it working the way I think it should. From what I have read, you can use the @Injectable decorator on a class and then the metadata is created for the DI like so:

import {Hero} from './hero.model';
import {Injectable} from 'angular2/angular2'

@Injectable()
export class HeroService {
    constructor() {
        console.log('Hero Service Created');
    }
}

Then in your component, you can use it in your constructor (with the proper import) like this:

constructor(heroService: HeroService) {
    console.log('App Component Created');
}

However, I get the following error: Cannot resolve all parameters for AppComponent(?). Make sure they all have valid type or annotations.

I am able to get it working properly if I remove the @Injectable syntax from the service and instead have my constructor like this:

constructor(@Inject(HeroService) heroService: HeroService) {
    console.log('App Component Created');
}

With everything that I've read, these should do the same thing, but they aren't. Any ideas as to why? I am using Typescript 1.6.2 with VS 2013, angular 2 v2.0.0-alpha.46, and systemjs v0.19.5.

Upvotes: 1

Views: 638

Answers (1)

alexpods
alexpods

Reputation: 48477

Make sure that you've specified "emitDecoratorMetadata" option in your TypeScript configuration.

Upvotes: 2

Related Questions