简体   繁体   中英

Confusing Angular 2+ modules, exports and services - how to avoid multiple instances of shared/reusable service

Given import { HttpModule } from '@angular/http'; that I import to my main application module ( BrowserModule ), and given that in the application I do DI of Http service all over the place, what will happen if:

  • I use some other module eg I created a feature module or I've downloaded npm package, let's call it CoolFeaturesModule
  • CoolFeaturesModule itself is importing HttpModule and injecting Http service

As far as I work it out, each module will have its own injector, and each injector will have a Http service provider registered. As a result I will have multiple instances of Http service. Is that correct?

There will be multiple instances of services based on angular.io docs

Dependencies are singletons within the scope of an injector. An application may have multiple injectors. An Angular application is a tree of components. Each component instance has its own injector. The tree of components parallels the tree of injectors.

As said, injetables are singleton only if they are available in the dependency injection tree. When injectables are used, firstly component checks it's dependency array, if found, it uses it. If not it climbs up to upper tree till AppModule. In this conidition, as you can see, if components/modules are siblings (or not just somehow inherited each other) and if they provide their own HttpService, they will separately initialize it.

However, If you do not use lazy loading, all your services will already be recognized at your main module. So in any case, your services will be global and thus singleton.

https://plnkr.co/edit/JpEDf1pxO95knVUQLwdE?p=preview

 import {Component, NgModule, VERSION,Injectable} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    import {HttpModule,Http} from "@angular/http";

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}


@Injectable() 
export class CustomHttpService{
  constructor(protected http: Http){

  }
}

@NgModule({
  imports:[HttpModule]
  providers:[CustomHttpService]
})
export class CustomHttpModule{}



@NgModule({
  imports: [ BrowserModule,CustomHttpModule],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM