Angular Providers or Providedin

402 Views Asked by At

I just can't seem to find the right way on how to use providers and provided in in Angular. I really did read the documentation on the subject, but there is a basic thing I just cannot get clear.

Suppose I have a service my.service.ts as below where I use ProvidedIn:'root'

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class MyService  {

  constructor() {
  }
  public Addup(a:number, b:number) : number
  {
    return a+b;
  }
}

I want that service to be available in the whole SPA as a singleton. I can inject that service in every module where needed all works fine. As in

    import {MyService} from '@services/my.service'
    @Component({
    ....
    })
    constructor (...
    private myService: MyService  ,
    ...){}

ngOnInit(): void {
const c = myService.Addup(2,4);
}

Works all as expected. BUT, Should I also add it to the providers section of the app.module.ts? When I do so it looks like there is no difference in behaviour at all?

app.module.ts:

import {MyService} from '@services/my.service'
...
...
@NgModule({
Declarations [...],
Imports: [...],
providers: [MyService,....]
}
export class AppModule {}

Can someone shed a light on this? Is ProvidedIn:'root' in the service the same as adding it to the providers array in the appModule?

Thanks.

1

There are 1 best solutions below

0
Zsolt Balint On

The root option registers the service in the Root Module Injector of the Module Injector tree. This will make it available to the entire application. This is irrespective of whether the service is lazy loaded or eagerly loaded.

And it will have the same outcome like providing the service in the app module. ProvidedIn is tree-shakeable, but beware of circular references if you simply try to import the same module that the components consuming the clients are declared in.