angular - How to share services - NgModule - Angular2 -
i know in angular2, services provided module available other modules , should provided once.
i have lazy-loaded messengermodule imports messengerservice. have headermodule needs service updating messages notifications.
i see 2 ways:
- provide messengerservice @ appmodule level
- provide messengerservice in messengermodule. import messengermodule in headermodule.
in 1, annoying "break" messengermodule removing logical service. in 2, lose lazy loaded feature of messengermodule quite big. headermodule eager loaded, messenger right?
it seems best choice provide service @ main level. suggestions?
you should read this article.
it involves: app/shared/shared.module.ts
import { ngmodule, modulewithproviders } '@angular/core'; import { counterservice } './counter.service'; @ngmodule({}) export class sharedmodule { static forroot(): modulewithprovider`enter code here`s { return { ngmodule: sharedmodule, providers: [counterservice] }; } } app/app.module.ts
import { sharedmodule } './shared/shared.module'; @ngmodule({ imports: [ sharedmodule.forroot(), ... ], ... }) export class appmodule {} since sharedmodule consists of service angular registers in root app injector, not need import in lazymodule. because lazy loaded module have access services defined @ root level.
Comments
Post a Comment