我刚开始使用 Angular2 快速启动项目。有一个简单的应用程序工作。我添加了 DataService 类,这样代码就会有关注点分离。

最初,我在应用程序的主要组件之后添加了 DataService 类 write,如下所示。

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)

上面的代码编译正确,但在运行时它会抛出以下错误。



在玩了 2 个小时的代码后,我将 MyAppComponent 移到了 DataService 的正上方,它起作用了。我真的很高兴这个问题得到了解决。

但是我很想知道,如果我将 MyAppComponent 类放在 DataService 之后,然后将 class 放在上面,为什么它不起作用?

编辑

我尝试了@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();
    }
}

但仍然在控制台中出错。看起来很奇怪

最佳答案

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.
    }
}

也可以看看
- Angular 2 error:
- http://blog.thoughtram.io/angular/2015/09/03/forward-references-in-angular-2.html

关于javascript - 如果类是在带有元注释的组件之后定义的,则该类不可注入(inject),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34838804/

10-11 09:16