1

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

That's the only thing I could think of too. @Rob here's a basic plunker with a simple service with working DI. The Cars Component uses the cars service. plnkr.co/edit/8ILuwhtxAP3g9o6u6jAQ?p=preview
This got me going in the right direction. Since I am developing within visual studio and having it compile my TS files, I had to add this to my csproj file: <TypeScriptAdditionalFlags> $(TypeScriptAdditionalFlags) --emitDecoratorMetadata </TypeScriptAdditionalFlags>
Better yet, instead, add this to your csproj file so that it will compile on save and not just on build: <TypeScriptEmitDecoratorMetadata>true</TypeScriptEmitDecoratorMetadata>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.