Currently, I am using VS2015 alongside TypeScript 1.7.3 and Angular2 Beta 2 with a target of ECMA 5. In order to enable experimental decorators in my project, I have made modifications to the csproj file by including
TypeScriptExperimentalDecorators = true
.
While following the Angular2 tutorial, I encountered difficulties getting dependency injection to function as expected. Strangely, the only way I can get DI to work is by adding @Inject
in the constructor of the AppComponent
class. If I omit @Inject
, an error occurs:
EXCEPTION: Cannot resolve all parameters for AppComponent(?). Make sure they all have valid type or annotations.
I refrained from providing the specific code here since it aligns with the tutorial content. However, I did attempt modifying boot.ts as shown below:
bootstrap(AppComponent, [HeroService]);
Despite this change, the error persisted. Is anyone else familiar with this issue?
The HeroService
utilizes the @Injectable
decorator:
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; }
}