为什么我不能在@NgModule中导入Angular 2服务?
我有ExchangeService
角2 @Injectable
类和我有一个应用程序主模块:为什么我不能在@NgModule中导入Angular 2服务?
@NgModule({
imports: [
BrowserModule,
HttpModule,
FormsModule,
ReactiveFormsModule,
ExchangeService,
RouterModule.forRoot(routes)
],
providers: [
{ provide: LocationStrategy,
useClass: HashLocationStrategy
},
ExchangeService
]
...})
这就引起异常
(index):16 Error: (SystemJS) Unexpected value 'ExchangeService' imported by the module 'Application5'
Error: Unexpected value 'ExchangeService' imported by the module 'Application5'
Error: (SystemJS) Unexpected value imported by the module Error: Unexpected value imported by the module
Error: Unexpected value imported by the module at eval (http://127.0.0.1:8080/node_modules/@angular/compiler/bundles/compiler.umd.js:13982:37) at Array.forEach (native) at CompileMetadataResolver.getNgModuleMetadata
Error: Unexpected value imported by the module at eval at Array.forEach (native) at CompileMetadataResolver.getNgModuleMetadata
当我从imports
子句除去ExchangeService
(我留在异常消失providers
子句)。我没有(目前)明确需要ExchnageService
在imports
条款(我不知道它有什么好处),我只想ExchangeService
可用于全局组件中的其他服务的注入。
问题是 - 为什么我不允许在imports
条款中写ExchangeService
条款?Imports
子句也包含其他TypeScript类 - 如HttpModule
等等以及为什么imports
子句不允许包含ExchangeService
?
你应该导入内部提供商
从
imports: [
BrowserModule,
HttpModule,
FormsModule,
ReactiveFormsModule,
RouterModule.forRoot(routes)
]
进口删除:用于导入支撑模块喜欢FormsModule,RouterModule,CommonModule,或任何其他定制的功能模块。
阅读本what-is-difference-between-declarations-providers-and-import-in-ngmodule
- 使用
imports
可以使其它(FormsModule,HTTP模块和等),您的当前模块中可用的模块。 - 使用
providers
可以通过注入组件,其它服务,管道所需的服务等
imports
用于导入当前模块中其它角模块。
providers
用于告诉角度哪些类型(实际上:实例)可用于依赖注入。
angular module
是一个组件,指令,管道,服务等的汇编。它是一个抽象,有助于构建更大的项目,并包含其他地方编写的功能。
每个应用程序至少包含一个模块(您的案例中的主要模块)。当应用程序增长时,你会被诱惑分割成几个模块。
你的ExchangeService
大概不是一个模块,而只是一个服务(有一些方法的类)。应用程序的其他组件和服务可能取决于具体的ExchangeService实例,并且如果将ExchangeService添加到提供者数组中,Angular将创建它的一个实例并在创建时注入它作为依赖项,例如,组件(假定您将ExchangedService声明为组件构造函数的参数)。我建议阅读https://angular.io/docs/ts/latest/guide/architecture.html。根据我的2美分,对这些建筑构件的理解是成功使用Angular的必要条件。
我想通了,但我的问题是 - 服务ExchangeService和模块BrowserModule之间的区别是什么 - 为什么我应该导入一个,而不是导入其他? – TomR
服务和模块是两个不同的东西 – Sajeetharan
@TomR删除答案的任何理由? – Sajeetharan