Providers are just the instance of the service.
You can create them once and use them everywhere or you can create multiple instances.
Let's understand how do we use them in Angular
All the services are registered with Angular but they can't be used until we instantiate them. So first, we have to instantiate the services and we do that by using providers.
There are two ways to instantiate the service. First by using providers array and the second one is to use providedIn.
The first method Using Providers Array
To use the service globally, we can place the providers in AppModule. By doing this, the instance of that service is created and all the components or other services in the app will use the same instance.
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NewService } from './newService';
@NgModule({
declarations: [
AppComponent
],
providers: [NewService],
bootstrap: [AppComponent]
})
export class AppModule { }
To use the service inside any specific component, we can place the providers in ComponentModule. By doing this, the new instance of that service is created and all the child components will use the same instance(It'll override the parent instance).
import { Component, OnInit } from '@angular/core';
import { NewService } from './newService';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers:[NewService]
})
export class AppComponent implements OnInit {
constructor(private newService: newService) { }
ngOnInit() { }
}
NOTE: If you place providers in AppComponent, then all the components in that app can use that instance but other services won't have access to that instance. To make other services also use the same instance, place it in AppModule.
The second method using providedIn
You can use Injectable decorator to instantiate any service.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' | Type<any>
})
export class UserService {
}
If it is root, then the whole application has access to that service. It means Angular creates a single instance of that service and whole application uses the same instance.
If it has to be accessed in only specific module, we can do that by giving the module name for providedIn
@Injectable({
providedIn: AnyModule
})
One more advantage of using Injectable decorator to instantiate service is that, if the service is not at all used anywhere in that application, then it will not be there in compiled Angular Application.