在Angular 2中提供核心单例服务模块 [英] Provide core singleton services module in Angular 2

查看:52
本文介绍了在Angular 2中提供核心单例服务模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为本教程创建一些核心模块,除了一个细节外,我只想提供服务.所以我的CoreModule应该像-单身人士服务提供者,因为我不想像App版本< = RC4中那样在AppModule中提供大量服务.我试图做这些东西,但是没有用. 我做错了吗?感谢您的帮助.

I tried to create some core module for just like in tutorial except one detail, I want provide only services. So my CoreModule should be like - singleton services provider, because I don't want to provide tons of services in AppModule like in app versions <= RC4. I tried to do that stuff but it is not working. I did some mistake? Thanks for any help.

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.我尝试了不同的方式来完成提供给我的事情,然后发现了一个有趣的时刻.

Update 2. I tried different ways to do that things that was provided to me and I found an interesting moment.

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

When I import in COREModule singleton services via standard import it doesn't works but when I imported it via System.js aliases it is working now. I am really wondering how it works. Here is code

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
      ) {
  }

推荐答案

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

The best approach is to create module with providers. Keep in mind that if your service is in shared module, you may get multiple instances of it. Best idea then is to configure module with Module.forRoot.

按照惯例,forRoot静态方法同时提供和配置 同时提供服务.它需要一个服务配置对象,并且 返回ModuleWithProviders.

By convention, the forRoot static method both provides and configures services at the same time. It takes a service configuration object and returns a ModuleWithProviders.

这里是完整的文档关于它.

仅在根应用程序模块AppModule中调用forRoot.呼唤 在任何其他模块中,尤其是在延迟加载的模块中,它是 与意图相反,并且可能会产生运行时错误.

Call forRoot only in the root application module, AppModule. Calling it in any other module, particularly in a lazy loaded module, is contrary to the intent and is likely to produce a runtime error.

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

Remember to import the result; don't add it to any other @NgModule list.

@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

If you want to prevent reimport of the CoreModule

只有根AppModule才能导入CoreModule.坏事 如果延迟加载的模块导入了它,则会发生这种情况.

Only the root AppModule should import the CoreModule. Bad things happen if a lazy loaded module imports it.

@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]
    };
  }
}

这篇关于在Angular 2中提供核心单例服务模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆