如果类是在具有元注释的组件之后定义的,则类是不可注入的

Class is not injectable if it is defined right after a component with meta annotation

本文关键字:定义 注入 之后 如果 注释 组件      更新时间:2023-09-26

我刚刚开始了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