I am trying to create a service in Angular that should only be injectable within a specific module, not accessible outside that module.
I have a service MyService that I want to restrict so it can only be injected within MyModule and not in other modules of the application.
MyService (my.service.ts):
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // This allows the service to be available globally, which I want to avoid
})
export class MyService {
constructor() {
}
}
MyModule (my.module.ts):
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyService } from './my.service';
@NgModule({
declarations: [],
imports: [CommonModule],
providers: [MyService] // Service should only be injectable here
})
export class MyModule { }
I want MyService to be injectable only within MyModule, and if I try to inject it into components or services in other modules, it should not be available.
I Tried:
Providing the service at the module level (
providers: [MyService]inMyModule).Avoiding
providedIn: 'root'to limit global injection.
How can I ensure that MyService is only injectable within MyModule?