How to define an Angular internal service and make it not injectable outside of its module?

Viewed 950

Is there anyways to prevent a service from being injected outside of its original module?

Say that we're loading the projects.module.ts lazily and ProjectsModule is importing the ProjectsStoreModule. I have a service defined in ProjectsStoreModule that I don't want to be injected in the ProjectsModule, but it's ok to be injected anywhere inside the ProjectsStoreModule. I was wondering if there's a way to achieve this?

Note: ProjectsStoreModule does not have any Components so I can't provide the service to a component. The service that I want to be isolated is going to be injected in an Ngrx Effect which is a service.

What I did:

I registered the ProjectsService:

@Injectable({
    providedIn: ProjectsStoreModule
})
export class ProjectsService {
    ...
}

ProjectsModule:

@NgModule({
    ...
})
export class ProjectsModule {
    ...
    imports: [ProjectsStoreModule] 
}

This approach obviously caused so many Circular dependency warnings.

Then I tried to register the ProjectsService in the @NgModule decorator:

@NgModule({
    ...
    providers: [ProjectsService]
})
export class ProjectsStoreModule {
    ...
}

Now the problem is that, by importing the ProjectsStoreModule into the ProjectsModule, the service that I wanted to be an internal service will be available in the ProjectsModule.

Any help would be highly appreciated.

2 Answers

Don't provide it use the provider array of the module. Inject the service on the root component of the module, if the module has one. Or just provide it at any component declaration that inject the service. This will make the service only accessible for the component and its child component.

@Component({
    selector: "component",
    templateUrl: "./component.component.html",
    providers: [
       InternalServiceClass
    ]
})```

Yes there is a way to prevent service from being injected outside its original module.

First you'll have to create a module for your service i.e ProjectServiceModule

Later , register your service with the newly created ProjectServiceModule like below:

@Injectable({
    providedIn: ProjectsServiceModule
})
export class ProjectsService {
    ...
}

Now include the ProjectServiceModule in your NgModule :

@NgModule({
 imports :[ProjectServiceModule]
})
export class ProjectsStoreModule {
    ...
}

This solution will remove your circular dependency errors while building the application and also solve your problem as this module is imported only in the ProjectsStoreModule

Refer this link for more info

Related