如果类是在具有元注释的组件之后定义的,则类是不可注入的
Class is not injectable if it is defined right after a component with meta annotation
我刚刚开始了Angular2快速入门项目。有一个简单的应用程序工作。我添加了DataService
类,以便代码具有关注点分离。
最初,我在应用程序的主要组件之后添加了DataService
类写入,如下所示MyAppComponent
。
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 不会提升类。要么使用 forwardRef,DataService
移动到它自己的文件,要么将DataService
类移动到MyAppComponent
@Component({
'selector': 'my-app',
template: `<div *ngFor="#item of items">{{item}}</div>`,
directives: [NgFor],
providers: [forwardRef(() => DataService)] //taking service as injectable
})
export class MyAppComponent {
items: Array<number>;
constructor(@Inject(forwardRef(() => DataService)) service: DataService) {
this.items = service.getItems(); //retrieving list to bind on the UI.
}
}
参见
- 角度 2 错误:
- http://blog.thoughtram.io/angular/2015/09/03/forward-references-in-angular-2.html
相关文章:
- Ember服务在注入组件并在计算属性中使用后是未定义的
- 使用index.ts文件导出类会导致注入的构造函数中未定义
- 注入应用程序的角度控制器未定义
- 会话注入不适用于自定义类
- $injector:modulerr将自定义模块注入Angular应用程序
- 将自定义CSS注入WP Admin登录弹出iframe
- 在Angular 2中的另一个服务中注入自定义服务
- angularjs自定义模块与$http注入
- 当使用Angular1+ES6时,控制器函数中未定义依赖注入,控制器是一个类
- 角度 js 自定义服务/工厂无法注入控制器/配置
- 角度JS:$location注入未定义
- 使用 Karma 进行角度测试:注入控制器后,$controller() 未定义
- $scope未为角度注入依赖项定义
- 尽管注入了$http,但它在服务中是未定义的
- 自定义提供程序 $injector:modulerr 的角度依赖注入
- 如何将数据库中的 html 标签注入到我的指令的模板中,实际上是动态定义模板的根元素/标签
- 如果类是在具有元注释的组件之后定义的,则类是不可注入的
- Angular$route服务没有;t被按时注入到控制器中——最初在页面加载时未定义,但后来一切都像符咒一样工作
- 我可以将Javascript代码注入Chrome自定义选项卡吗
- Angular中的二重定义注入模