6

我正在浏览 angular2.0 演示应用程序,但似乎注射剂无法从 build 24 开始工作,并给我错误
“原始错误:无法解析 MyAppComponent 的所有参数。确保它们都有有效的类型或注释。”
直到 build 23 工作正常,请帮我解决
下面的问题是演示代码,我对原始代码做了一些操作,只是为了学习目的

import {Component, View, bootstrap, NgFor} from 'angular2/angular2';


module foo{
  class FriendsService {
    names: Array<string>;
    constructor() {
        this.names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana","Kai"];
    }
}


@Component({
    selector: 'array',
    injecetables: [FriendsService]

})
@View({
        template: '<p>My name: {{ myName }}</p><p>Friends:</p><ul><li *ng-for="#name of names">{{ name }}</li></ul>',
        directives: [NgFor]
}) 
   export class arrayComponent {
    myName: string;
    names: Array<string>;

    constructor(friendsService: FriendsService) {
       this.myName = 'Alice';
       this.names = friendsService.names;
     }
   }
 }

bootstrap(foo.arrayComponent);
4

5 回答 5

7

似乎当前最新的 angular2 alpha-35替换appInjectorbindings.

像这样:

import {FriendsService} from 'FriendsService';

@Component({
    selector: 'array',
    bindings: [FriendsService]
})

我还必须明确导出FriendsService

export class FriendsService {

完整的代码示例在这里

于 2015-08-30T16:53:10.623 回答
2

的新语法injectablesappInjector.

尝试:

@Component({
  selector: 'array',
  appInjector: [FriendsService]
})

此外,您还需要将导入更改ComponentView

import {ComponentAnnotation as Component, ViewAnnotation as View} from "angular2/angular2";
于 2015-06-11T12:13:46.683 回答
2

在 Angular 2 中有应用程序范围的注入器,然后是组件注入器。

如果您只想在整个应用程序中使用一个 FriendsService 实例,请将其包含在 bootstrap() 数组中:

@Component({
   // providers: [FriendsService],
   ...

bootstrap(App, [FriendsService])

如果您希望每个组件有一个实例,请改用providers组件配置对象中的数组:

@Component({
   providers: [FriendsService ],
   ...

bootstrap(App, [])

Plunker

有关更多信息,请参阅Hierarchical Injectors文档。

于 2015-11-14T23:44:03.927 回答
0

模块 foo{ 类 FriendsService {...

您的FriendsService类是在一个模块中定义的,这在两个方面是一个问题:

  1. 您的类需要从模块中导出以使其在外部可见foo
  2. 当您引用时,FriendsSerivce您并没有指定它在foo模块内部。

我建议完全删除 foo 模块并改用 amd/commonjs 中的模块模式。这意味着您不需要导出类(假设它们在同一个文件中),也不需要更改组件中对类的引用。

于 2015-06-12T10:52:33.737 回答
0

FriendsService在模块中被抽象并且没有被导出,这就是为什么arrayComponent无法访问它并引发错误。

您应该只取出模块并foo在上面arrayComponent的相同范围内声明。

此外,您最后的引导程序是错误的,因为arrayComponent它不是foo. 就这样吧

bootstrap(arrayComponent)

应该没问题。

于 2015-07-19T04:21:57.983 回答