I thought I understood Angular modules, but am having trouble figuring out the best approach for structuring modules involving services and components to be provided by a library.
The library implements a NotificationsComponent
, which depends on a NotificationsService
, which needs to be a singleton since it persists notification information. The consumer wants to use the NotificationsComponent
in various pages, some of which are inside an AdminPagesModules
, and others are inside an BookPagesModule
.
Let's say in the library I define a NotificationsModule
, which "declares" and "exports" NotificationsComponent
, and "provides" NotificationsService
. Now if I import this module into both AdminPagesModule
and BookPagesModules
so pages in those modules can use NotificationComponent
, I get separate instances of the NotificationsService
, which won't work. On the other hand, if I import NotificationsModule
in my AppModule
, I succeed in making sure NotificationsService
is a singleton used throughout the app, but I cannot see NotificationsComponent
inside the components inside the individual feature modules such as AdminPagesModule
.
I have seen a pattern where one module imports another module, then re-exports it. In this case, we would import NotificationsModule
in AppModule
, and then re-export it, then import NotificationsModule
again in AdminPagesModule
. In this case, will NotificationsService
be a singleton across the app, as I want, yet NotificationsComponent
still be available to components inside AdminPagesModule
?
Or is there an approach to this problem involving the SharedModule
pattern?
Best to put singleton Services in a separate ts file and import/provide once and only once either in AppModule or SharedModule, not the component module (eg library). Components declared in modules that are imported into AppModule will be available in templates throughout the app, and do not need to be re-declared or exported.
Also see https://stackoverflow.com/a/39665993/3103979
Example of services provided in a SharedModule:
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [
...
ApiService,
Auth,
...
]
};
}
}
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.