angular 2.0最新版本26中无法使用的注射剂
我正在浏览angular2.0演示应用程序,但似乎injectables无法从build 24开始工作,给我的错误是“原始错误:无法解析MyAppComponent的所有参数。请确保它们都具有有效的类型或注释。”angular 2.0最新版本26中无法使用的注射剂,angular,typescript1.5,Angular,Typescript1.5,我正在浏览angular2.0演示应用程序,但似乎injectables无法从build 24开始工作,给我的错误是“原始错误:无法解析MyAppComponent的所有参数。请确保它们都具有有效的类型或注释。”在build 23之前,它工作正常,请帮助我解决此问题 下面是演示代码,我对原始代码做了一些操作,只是为了学习 import {Component, View, bootstrap, NgFor} from 'angular2/angular2'; module foo{ cla
在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);
从'angular2/angular2'导入{组件、视图、引导、NgFor};
模块foo{
班级友谊服务{
名称:数组;
构造函数(){
this.names=[“Alice”、“Aarav”、“Martín”、“Shannon”、“Ariana”、“Kai”];
}
}
@组成部分({
选择器:“数组”,
injecetables:[朋友服务]
})
@看法({
模板:“我的名字:{{myName}朋友:”,
指令:[NgFor]
})
导出类arrayComponent{
我的名字:字符串;
名称:数组;
构造函数(friendsService:friendsService){
this.myName='Alice';
this.names=friendsService.names;
}
}
}
引导(foo.arrayComponent);
注入式的新语法是appInjector
尝试:
此外,您还需要将组件
和视图的导入更改为:
import {ComponentAnnotation as Component, ViewAnnotation as View} from "angular2/angular2";
模块foo{
班级友谊服务{
您的FriendsService
类是在模块中定义的,该模块有两种问题:
您的类需要从模块中导出,以使其在foo
当您引用Friendserive
时,您没有指定它在foo
模块中
我建议完全删除foo模块,转而依赖amd/commonjs中的模块模式。这意味着您不需要导出类(假设它们在同一个文件中)而且您不需要更改对组件中类的引用。您的FriendsService
在模块中被抽象,并且没有被导出,这就是arrayComponent
无法访问它并抛出错误的原因
您只需取出模块,并在相同范围内的arrayComponent
上方声明foo
另外,由于arrayComponent
不是foo
的一部分,因此最后的引导是错误的
bootstrap(阵列组件)
它应该很好。似乎用绑定取代了appInjector
像这样:
从“FriendsService”导入{FriendsService};
@组成部分({
选择器:“数组”,
绑定:[FriendsService]
})
我还必须明确导出FriendsService
:
导出类友服务{
在Angular 2中,有应用范围内的喷油器,然后是部件喷油器
如果整个应用程序中只需要一个FriendsService实例,请将其包含在bootstrap()数组中:
如果您希望每个组件有一个实例,请在组件的配置对象中使用提供程序数组:
@Component({
providers: [FriendsService ],
...
bootstrap(App, [])
查看文档以了解更多信息。上述解决方案不起作用,仍然给我相同的错误,我的上述代码中是否还有其他我缺少的内容appInjector
已被删除@alpha.29,此解决方案将不再起作用。现在必须使用hostInjector
或viewInjector
我遇到了上述相同的问题,我“我尝试了hostInjector和viewInjector,但仍然出现相同的错误。您能指出一些说明如何正确使用它们的内容吗?@klas melbourn谢谢!我注意到您没有使用bootstrap()
来自指南-有什么原因吗?export
取代了它吗?@ghchinoy我在主app.ts
文件中使用bootstrap
。你只需要做一次,而不是在每个.ts
文件中都做一次。@ghchinoy,如果你使用bootstrap()
,则您使用的是应用程序范围的注入器,您将只获得一个FriendsService
实例。如果您在组件上使用提供程序
(它将替换绑定
),则您正在使用组件的注入器,您可能会获得多个FriendsService
实例。有关更多信息,请参阅我的答案。
@Component({
// providers: [FriendsService],
...
bootstrap(App, [FriendsService])
@Component({
providers: [FriendsService ],
...
bootstrap(App, [])