Thursday, August 13, 2020

Angular Service Scope

In Angular, Services are a great way to share information among Components that don't know each other. Based on how we register a service we can control the scope/visibility of the service across the Application.

Services can be registered with 3 levels of scope
1. Global Scope
2. Module Scope
3. Component Scope

Global Scope

When a service is registered with a root provider the same instance of the service is shared across all components in the Angular App

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

export class HelloService {
  constructor() { }
}

Module Scope
When a service is registered with a specific NgModule the service instance is shared only within components in that module. To do this we will have to add the service to the providers[] array of the module.
@NgModule({
  providers: [ HelloService ],
})

Component Scope
When a service is registered with a specific Component, a new instance of the service is created each time when the component is created. To do this we will have to add the service to the providers[] array if the component.

@Component({
  selector:    'app-hello',
  templateUrl: './hello.component.html',
  providers:  [ HelloService ]
})


Search Flipkart Products:
Flipkart.com

No comments: