javascript - 为什么我不能在@NgModule 中导入 Angular 2 服务?

标签 javascript angular typescript

我有 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 子句中),异常消失了。我(目前)不明确需要 ExchnageServiceimports 子句中(我不知道它有什么好处),我只想要 ExchangeService 可用于在全局组件中的其他服务中注入(inject)。

问题是 - 为什么不允许我在 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

关于javascript - 为什么我不能在@NgModule 中导入 Angular 2 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43388811/

相关文章:

javascript - 自动重定向到扫描的链接

angular - Ionic Capacitor Camera,生成完整质量图像并在不生成 Base64 和 DataUri 的情况下显示它

Angular 2 : "Expected the operants to be of similar type or any" linting error

javascript - 如何序列化可观察数组的执行

reactjs - 如何在 TypeScript 中动态更新类型对象上的键值对

javascript - id动态生成时获取链接的id

javascript - Angular JS ng-repeat 从数组中选择随机分组?

html - Angular 标签破坏了 CSS 样式

javascript - AngularJS 和 Q.fcall

javascript - Jquery全局数组变量和动态创建按钮问题