How can I make an Angular service injectable only within a specific module?

Discussão em 'Angular' iniciado por Buffden, Setembro 10, 2024.

  1. Buffden

    Buffden Guest

    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:


    1. Providing the service at the module level (providers: [MyService] in MyModule).


    2. Avoiding providedIn: 'root' to limit global injection.

    How can I ensure that MyService is only injectable within MyModule?

    Continue reading...

Compartilhe esta Página