Jayan Patel
Jayan Patel

Reputation: 1

How to share singleton service with two different lazy loaded module in angular 6 without providing it in AppModule providers?

I have two different lazy loaded modules like module A and Module B. I have a common view of both the module. so I have created a shared module with a shared component and shared service. as shown below.

shared module.

@NgModule({ imports: [ CommonModule, 
], declarations: [ComponentA], exports: [ComponentA], providers: [ComponentAService]

}) export class SharedModule { static forRoot(): ModuleWithProviders { return { ngModule: SharedModule, providers: [ComponentAService] }; } }

Component A

export class ComponentA { constructor(private componentAService: ComponentAService ) }

*) Module A

const routes: Routes = [{ path: '', component: ComponentA canActivate: [AuthGuard], ];

@NgModule({ imports: [ CommonModule, SharedModule, RouterModule.forChild(routes), 
], exports: [], declarations: [], providers: [] })

Module B

const routes: Routes = [{ path: '', component: ComponentA canActivate: [AuthGuard], ];

@NgModule({ imports: [ CommonModule, SharedModule, RouterModule.forChild(routes), 
], exports: [], declarations: [], providers: [] })

Here I observed that it creates two different instances of service for both the module i.e ModuleA & Module B I want a single service object for both the modules and without registering my service in APPModule.

Upvotes: 0

Views: 486

Answers (2)

Incognita
Incognita

Reputation: 99

There is no need to register a service for a module, if your service is going to be shared in more than one module then provide it in either shared or app module.

@Injectable({
    providedIn: 'root'
})

export class commonService() {
}

Upvotes: 0

Kiran Shinde
Kiran Shinde

Reputation: 5982

You don't have to register your service in any module.

What you have to do is

in your service add these lines before class definition

@Injectable({
    providedIn: 'root'
})

// your sevice class
export class ComponentAService {}

thats it, don't register your service in any module or any components

Upvotes: 1

Related Questions