Monday, 19 April 2021

What is/are service(s)

Services & DI (in aspect of angular)
  • What is service?
  • Why we need?
  • How to use service in angular?
  • What is DI (Dependency Injection)
  • What is Injector in Angular Services 
  • Hands On Services & DI
  • More on Angular Services (How they actually works)
A plain type script class for well-defined purpose that’s it, nothing else.

Export class EmployeeeService{

constructor (){

        }
}

Why Services?

  • DRY
  • Separation of concerns
  • To Increase modularity & reusability 
  • https://angular.io/guide/architecture-services - Angular docs also ask for same

How to use services in Angular?

  • Create a service class (best to use Robot )
  • Register service with angular (Injector).
  • Inject/use service using (Dependency Injection )

Dependency Injection

  • Code without DI - Drawbacks
  • DI as Design Pattern
  • DI as Framework in context of Angular
Code without  DI - Drawbacks



DI as Design Pattern
  • DI is a coding pattern in which a class receives it dependencies from external sources rather than creating it from itself

DI as Design Pattern Cont.


Dependency Injection as Framework using Injector

  • Injector is nothing but just like a container in angular framework which keeps track or list of all dependencies.
  • When any components or elements would required any dependency then injector is responsible to provide that dependency at the time of initialization.


Let’s get back to hands on Services
  • Create a service class (best to use robot) - done
  • Register service with angular (Injector). - done
  • Inject/use service using (Dependency Injection )



More on Services : Ways of Registering services 

Module Injector
  • With-in provider section of @NgModule decorator 
  • Using @Injectable decorator with meta data 


Element Injector
  • created implicitly at each DOM element (@Component, @Directive)

Note : Registration of services in angular follows the hierarchy system and it would be responsibility of  Injector (by whom it can be injected & by whom can be not). 

Register at Child component level


Register at Parent component level




Register at module/root level




More on Services : ‘root’ || ‘platform’ || any




More on Services : Deep Dive




  • Which one is better Module Injector (@NgModule or @Injectable)
  • @Injectable annotation (what else this annotation do apart from registration)
  • Is Angular services are Singleton?  
  • What is Sandboxing ?



No comments:

Post a Comment