How do you restrict provider scope to a module?

It is possible to restrict service provider scope to a specific module instead making available to entire application. There are two possible ways to do it.

  1. Using providedIn in service:

    import { Injectable } from '@angular/core';
    import { SomeModule } from './some.module';
    @Injectable({
    providedIn: SomeModule,
    })
    export class SomeService {}
  2. Declare provider for the service in module:

    import { NgModule } from '@angular/core';
    import { SomeService } from './some.service';
    @NgModule({
    providers: [SomeService],
    })
    export class SomeModule {}

June 07, 2022
1064