【发布时间】:2025-11-24 03:35:01
【问题描述】:
我刚开始使用 Angular2 快速启动项目。有一个简单的应用程序工作。我添加了DataService 类,这样代码就会有关注点分离。
最初我在应用程序的主要组件 MyAppComponent 之后添加了 DataService 类,如下所示。
import {Component, View} from 'angular2/core';
import {NgFor} from 'angular2/common';
import {bootstrap} from 'angular2/platform/browser';
@Component({
'selector': 'my-app',
template: `<div *ngFor="#item of items">{{item}}</div>`,
directives: [NgFor],
providers: [DataService] //taking service as injectable
})
export class MyAppComponent {
items: Array<number>;
constructor(service: DataService) {
this.items = service.getItems(); //retrieving list to bind on the UI.
}
}
//created service, but its after the component which has meta annotation
export class DataService {
items: Array<number>;
constructor() {
this.items = [1, 2, 3, 4];
}
getItems() {
return this.items; //return the items list
}
}
bootstrap(MyAppComponent)
上面的代码编译正确,但在运行时会抛出下面的错误。
例外:无法解析所有参数 MyAppComponent(未定义)。确保它们都具有有效的类型或 注释。
在使用代码 2 小时后,我将 DataService 移到了 MyAppComponent 的上方,这已成功。我真的很高兴这个问题解决了。
但我很想知道,如果我在 class 之后放置 DataService 类并在其上放置 MetaAnnotation,为什么它不起作用?
编辑
我尝试了@Günter Zöchbauer 提供的解决方案,如下所示,
import {Component, View, Inject, forwardRef} from 'angular2/core';
import {NgFor} from 'angular2/common';
import {bootstrap} from 'angular2/platform/browser';
@Component({
'selector': 'my-app',
template: `<div *ngFor="#item of items">{{item}}</div>`,
directives: [NgFor],
providers: [DataService] //tried commenting this still throws error.
})
export class MyAppComponent {
items: Array<number>;
constructor(@Inject(forwardRef(() => DataService)) service: DataService) {
this.items = service.getItems();
}
}
但在控制台中仍然出现错误。看起来很奇怪
异常:类型错误:无法读取未定义的属性“toString”
【问题讨论】:
标签: javascript dependency-injection ecmascript-6 angular