在Angular 2中提供核心单例服务模块

时间:2016-10-06 08:04:46

标签: angular typescript

我尝试创建一些核心模块,就像在教程中除了一个细节,我想只提供服务。所以我的CoreModule应该像 - 单身服务提供商,因为我不想在AppModule中提供大量服务,就像应用版本< = RC4一样。我试着做那些东西,但它不起作用。 我做错了吗?谢谢你的帮助。

import {
  ModuleWithProviders, NgModule,
  Optional, SkipSelf }       from '@angular/core';

import { CommonModule }      from '@angular/common';

import { CommunicatePatientListService }    from './services/communicate_patients_list.service';
import { HTTPPatientsListService }    from './services/http_patients_list.service';
import { SharedService }    from './services/shared_service';


@NgModule({
  imports:      [ CommonModule ],
  providers:    [
    CommunicatePatientListService,
    HTTPPatientsListService,
    SharedService
  ],
  exports: []
})
export class CoreModule {}

更新2.我尝试了不同的方法来完成提供给我的事情,我发现了一个有趣的时刻。

当我通过标准导入导入COREModule单例服务时,它不起作用,但是当我通过System.js别名导入它时,它现在正在工作。我真的很想知道它是如何工作的。这是代码

CoreModule:
import {
  ModuleWithProviders, NgModule,
  Optional, SkipSelf }       from '@angular/core';

import { CommonModule }      from '@angular/common';


import { HeaderModule } from './modules/header/header.module';
import { FooterComponent } from './modules/footer/footer.component';


//THAT DOESNT WORK
// import { CommunicatePatientListService }    from './services/communicate_patients_list.service';
// import { HTTPPatientsListService }    from './services/http_patients_list.service';
// import { SharedService }    from './services/shared_service';
// import { SchedulerSharedService }    from './services/scheduler_shared.service';
// import { FormChangeService }    from './services/on_form_change.service';

//IT IS WORKING NOW
import { CommunicatePatientListService } from '%sharedServices%/communicate_patients_list.service';
import { HTTPPatientsListService } from 'httpPatientsListService';
import { SharedService } from 'sharedService';
import { SchedulerSharedService } from 'schedulerSharedService';
import { FormChangeService } from 'formChangeService';



@NgModule({
  imports:      [
    CommonModule,
    HeaderModule,
  ],
  declarations: [
    FooterComponent
  ],

  exports: [
    FooterComponent,
    HeaderModule
  ]
})
export class CoreModule {

  constructor (@Optional() @SkipSelf() parentModule: CoreModule) {
    if (parentModule) {
      throw new Error(
        'CoreModule is already loaded. Import it in the AppModule only');
    }
  }

  static forRoot(): ModuleWithProviders {
    return {
      ngModule : CoreModule,
      providers:    [
        CommunicatePatientListService,
        HTTPPatientsListService,
        SharedService,
        FormChangeService,
        SchedulerSharedService
      ]
    };
  }


}

患者列表组件

import { Component, Input, OnInit, ViewChild } from '@angular/core';

import { CommunicatePatientListService } from '%sharedServices%/communicate_patients_list.service';
    import { HTTPPatientsListService } from 'httpPatientsListService';
    import { SharedService } from 'sharedService';
    import { SchedulerSharedService } from 'schedulerSharedService';
    import { FormChangeService } from 'formChangeService';

    import { Config } from 'appConfig';
    /* ------- !Config  ---------*/

    const MODULE_NAME: string = 'patients_list';
    const MODULE_PATH: string = `${Config.getProdFolderName()}/modules/patients/${MODULE_NAME}`;


    @Component({
      templateUrl: `${MODULE_PATH}/${MODULE_NAME}.component.html`,
      styleUrls: [`${MODULE_PATH}/${MODULE_NAME}.component.css`,]
    })


    export class PatientsListComponent implements OnInit {
      constructor(
        private patientsListService:HTTPPatientsListService,
        private patsListServCom:CommunicatePatientListService,
        private schedulerSharedService:SchedulerSharedService,
        private sharedService:SharedService
      ) {
  }

1 个答案:

答案 0 :(得分:14)

最好的方法是使用提供程序创建模块。请记住,如果您的服务位于共享模块中,您可能会获得多个实例。最好的办法是使用Module.forRoot配置模块。

  

按照惯例,forRoot静态方法既提供又配置   服务同时进行。它需要一个服务配置对象和   返回一个ModuleWithProviders。

以下是关于它的完整Doc

  

仅在根应用程序模块AppModule中调用。调用   它在任何其他模块中,特别是在延迟加载的模块中,是   与意图相反,可能会产生运行时错误。

     

记得导入结果;不要将它添加到任何其他@NgModule   列表。

@NgModule({
    imports: [CommonModule],
    declarations: [SomeComponent],
    exports: [SomeComponent]
})
export class CoreModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: CoreModule,
            providers: [SomeService]
        };
    }
}

然后导入模块如下:

@NgModule({
  imports: [
    /** other modules import **/
    CoreModule.forRoot(), // you can also pass some config here if needed
    routing
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

如果您想阻止重新导入CoreModule

  

只有根AppModule才能导入CoreModule。坏事   如果延迟加载的模块导入它,就会发生。

@NgModule({
  imports:      [ CommonModule ],
  declarations: [ SomeComponent ],
  exports:      [ SomeComponent ],
})
export class CoreModule {

  constructor (@Optional() @SkipSelf() parentModule: CoreModule) {
    if (parentModule) {
      throw new Error(
        'CoreModule is already loaded. Import it in the AppModule only');
    }
  }

  static forRoot(config: UserServiceConfig): ModuleWithProviders {
    return {
      ngModule: CoreModule,
      providers: [SomeService]
    };
  }
}