whitemtnelf
whitemtnelf

Reputation: 181

Visual Studion 2015 and Angular2 Beta 2 dependency injection

My environment is VS2015 with TypeScript 1.7.3, Angular2 Beta 2, target ECMA 5. I've modified the csproj file to include TypeScriptExperimentalDecorators = true.

I'm working on the Angular2 tutorial and can not get dependency injection working as documented. I can only get DI to work when I include @Inject in the AppComponent class constructor. If I don't include @Inject I receive this error -

EXCEPTION: Cannot resolve all parameters for AppComponent(?). Make sure they all have valid type or annotations.

I did not include the code in this post because its the same as the tutorial. I did try modifying boot.ts as follows:

bootstrap(AppComponent, [HeroService]);

but I still get the error. Has anyone else run into this?

The HeroService is decorated with @Injectable:

import {Hero} from './hero';
import {HEROES} from './mock-heroes';
import {Injectable} from '../node_modules/angular2/core';

@Injectable()
export class HeroService {
    heroes: Hero[];

    getHeroes() {
        return Promise.resolve(HEROES);
    }
   //  See the "Take it slow" appendix
    getHeroesSlowly() {
        return new Promise<Hero[]>(resolve =>
            setTimeout(() => resolve(HEROES), 2000) // 2 seconds
        );
    }
}

app.component.ts

import {Component, OnInit, Inject} from '../node_modules/angular2/core';
import {Hero} from './hero';
import {HeroDetailComponent} from './hero-detail.component';
import {HeroService} from './hero.service';

@Component({
    selector: 'my-app',
    template: `
        <h1>{{title}}</h1>
        <my-hero-detail [hero]="selectedHero"></my-hero-detail>
        <h2>My Heroes</h2>
        <ul class="heroes">
            <li *ngFor="#hero of heroes" 
                (click)="onSelect(hero)" 
                [class.selected]="hero === selectedHero">
                <span class="badge">{{hero.id}}</span> {{hero.name}}
            </li>
        </ul>      
        `
    ,directives: [HeroDetailComponent]
    ,providers: [HeroService]
})

export class AppComponent implements OnInit {
    public title = 'Tour of Heroes';
    public heroes: Hero[];
    public selectedHero: Hero;

    constructor(private _heroService: HeroService) { 
   // constructor( @Inject(HeroService) private _heroService: HeroService) {

    }
    getHeroes() {
        this._heroService.getHeroes().then(heroes => this.heroes = heroes);
    }
    ngOnInit() {
        this.getHeroes();
    }
    onSelect(hero: Hero) { this.selectedHero = hero; }
}

Upvotes: 1

Views: 369

Answers (1)

whitemtnelf
whitemtnelf

Reputation: 181

I solved the problem by adding the following to the csproj file and was able to remove the @Inject from the code -

<TypeScriptEmitDecoratorMetadata>true</TypeScriptEmitDecoratorMetadata>

See here for how to set TS compiler options in Visual Studio

Upvotes: 1

Related Questions