[英]Can I use an angular service without mentioning it in NgModule's providers?
[英]Why I cannot import Angular 2 service in @NgModule?
我有ExchangeService
Angular 2 @Injectable
類,我有一個應用程序主模塊:
@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)
]
imports:用於導入支持模塊,如FormsModule,RouterModule,CommonModule或任何其他定制的功能模塊。
閱讀這個what-is-difference-between-declarations-providers-and-import-in-ngmodule
imports
您可以在當前模塊中使用其他(FormsModule,HttpModule等)模塊。 providers
您可以注入組件,其他服務,管道等所需的服務。 imports
用於導入當前模塊中的其他角度模塊。
providers
用於告訴angular什么類型(實際上:實例)可用於依賴注入。
angular module
是組件,指令,管道,服務等的集合。它是一種抽象,有助於構建更大的項目並包含其他地方編寫的功能。
每個應用程序至少包含一個模塊(在您的情況下為主模塊)。 當應用程序增長時,您將被誘惑分成幾個模塊。
您的ExchangeService
可能不是模塊,而只是一個服務(具有某些方法的類)。 應用程序的其他組件和服務可能依賴於ExchangeService的具體實例,如果將ExchangeService添加到providers數組,Angular將創建它的實例並在創建組件時將其作為依賴項注入(假設您將ExchangedService聲明為組件構造函數的參數)。
我建議閱讀https://angular.io/docs/ts/latest/guide/architecture.html 。 根據我的2美分,對這些建築構建塊的理解是成功使用Angular所必需的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.