根据 Angular 2 的最终版本,模块提供的服务可供导入该模块的所有其他模块使用。
这官方风格指南 https://angular.io/docs/ts/latest/guide/style-guide.html#!#app-structure-and-angular-modules建议应由某些人提供将在应用程序中的任何位置重用的应用程序范围服务(单例)Core Module
,即要在main中导入App Module
所以它可以注射到任何地方。
如果您不使用涉及具有共享单例的核心模块的结构,并且您正在独立开发两个 NgModule,并且希望其中一个中的服务在另一个中使用,那么唯一的解决方案是将提供程序导入到另一个 :
这是提供者模块:
/// some.module.ts
import { NgModule } from '@angular/core';
import { SomeComponent } from './some.component';
@NgModule({
imports: [],
exports: [],
declarations: [SomeComponent],
providers: [ MyService ], // <======================= PROVIDE THE SERVICE
})
export class SomeModule { }
这是想要使用的另一个模块MyService
/// some-other.module.ts
import { NgModule } from '@angular/core';
import { SomeModule } from 'path/to/some.module'; // <=== IMPORT THE JSMODULE
import { SomeOtherComponent } from './some.other.component';
@NgModule({
imports: [ SomeModule ], // <======================== IMPORT THE NG MODULE
exports: [],
declarations: [SomeOtherComponent],
providers: [],
})
export class SomeOtherModule { }
这样,服务应该可以注入到任何组件中SomeOtherModule
声明,并在 SomeModule 本身中 - 只需在构造函数中请求它:
/// some-other.module.ts
import { MyService } from 'path/to/some.module/my-service';
/* ...
rest of the module
*/
export class SomeOtherModule {
constructor( private _myService: MyService) { <====== INJECT THE SERVICE
this._myService.dosmth();
}
}
如果这不能回答您的问题,我邀请您重新制定它。