我的环境是VS2015,带有TypeScript 1.7.3,Angular2 Beta 2,目标ECMA 5.我已经修改了csproj文件以包含TypeScriptExperimentalDecorators = true
。
我正在研究Angular2 tutorial,并且无法按照记录的方式使依赖注入工作。当我在@Inject
类构造函数中包含AppComponent
时,我才能使DI工作。如果我不包含@Inject
,我会收到此错误 -
EXCEPTION:无法解析AppComponent(?)的所有参数。确保它们都有有效的类型或注释。
我没有在这篇文章中包含代码,因为它与教程相同。我确实尝试修改boot.ts,如下所示:
bootstrap(AppComponent, [HeroService]);
但我仍然得到错误。还有其他人遇到过这个吗?
HeroService
饰有@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; }
}
答案 0 :(得分:1)
我通过在csproj文件中添加以下内容来解决问题,并且能够从代码中删除@Inject -
<TypeScriptEmitDecoratorMetadata>true</TypeScriptEmitDecoratorMetadata>
有关如何在Visual Studio中设置TS编译器选项的信息,请参阅here