Wednesday, March 25, 2020

Angular Service

Services in Angular are a great deal to share information among classes that do not know each other.  When we are developing the Angular app, we will most likely run into an outline in which we need to use the exact same code across multiple angular components. In that case, the Services will help us to get rid of that problem. We can share the services code among various angular components.
With Angular’s dependency injectionyou can inject the services around your app. 
Why we use Angular Service
There are many reasons why you would want to create and use the services in your Angular applications. One of the most common is the data service. The class that will handle getting and setting data from your datastore.
The data service that gets injected into each of those components allows you not to have to recreate the same datastore connection code in each component. Another common use of service is for some business logic.
The Angular framework has classes that are necessarily service classes. Things like HttpFormBuilder, and more, contain logic for doing specific things that are non-component specific. And again, through the dependency injection engine, you can get these services sent into your class constructors and use them.
Services in Angular provide an architectural way to encapsulate business logic in a reusable fashion, allowing you to keep that logic out of your components, directives, and pipe classes. This is not only beneficial for modularity, and single responsibility type of simplicity tier code, but it also makes the code more testable. 
If you employ a unit testing strategy, it becomes straightforward to mock the services that get used in a component. Thus your unit test can focus purely on confirming the behavior of the component and not its dependencies. 
Same goes for your services that get other services provided to them. So services, while not an enforced construct, are a fundamental building block to an Angular application.
In this case, Components use to display and present the data. Services use to fetch a data from an API. Let’s start our Angular Service Example. 
Angular 5 Service Example-1
Create a Service class: To create an angular service class, at the console, type the following command in your root of the folder.
ng g service services/myservice –flat true
create src\app\services\myservice.service.spec.ts
create src\app\services\myservice.service.ts
WARNING Service is generated but not provided, it must be provided to be used
It will create the following files.
  1. myservice.service.ts
  2. myservice.service.spec.ts


import { Injectable } from '@angular/core';
  providedIn: 'root'
export class MyServiceService {
  constructor() {}
Here, the Injectable module is imported from the @angular/core. It contains the @Injectable method and a class called MyserviceService. We will create our service function in this class.
Before creating a new service, we need to include the service created in the main parent app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MyserviceService } from './services/service1.service';
import { AppComponent } from './app.component';

  declarations: [
  imports: [
  providers: [Service1ServiceMyserviceService],
  bootstrap: [AppComponent]
export class AppModule {}

We have imported the Service with the class name and the same class is used in the providers. Let us now switch back to the service class and create a service function.
In the service class, we will create a function that will display today’s date.  
Let us now see how the function looks in the service and how to use it in components.

import { Injectable } from '@angular/core';
  providedIn: 'root'
export class MyserviceService {
  serviceproperty = 'Service Created and Injected';
  constructor() {}

  showTodayDate() {
    let ndate = new Date();
    return ndate;

In the above service file, we have created a function showTodayDate. Now we will return the new Date () created.
Let us now see how to use the service in the new component created.


import { ComponentOnInit } from '@angular/core';
import { MyserviceService } from '../services/myservice.service';

  selector: 'app-service-component',
  templateUrl: './service-component.component.html',
  styleUrls: ['./service-component.component.css']
export class ServiceComponentComponent implements OnInit {
  constructor(private myserviceMyserviceService) {}

  ngOnInit() {
    this.todaydate = this.myservice.showTodayDate();
    this.msg = this.myservice.serviceproperty;

The ngOnInit function gets called by default in any component created. The date is fetched from the service as shown above. To fetch more details of the service, we need to first include the service in the component .ts file.We will display the date in the Service-Component.component.html file as shown below –
  {{ msg }}
<h2>Today's Date : {{ todaydate }}</h2>

The selector of the new component is used in the app.component.html file. The contents from the above html file will be displayed in the browser as shown below –
Output (Service Example-1):

Global service vs. Local Service Injection in Angular 

( Dependency Injection )

To inject the service, you have the following two options.

1)     Inject as ‘global service.’

To inject as a global service, inject a service into the root module.
You need to register the module inside the app.module.ts file like we have done earlier in this post.
import { MyServiceService } from './services/Myservice.service'; 

@NgModule({ providers: [MyServiceService], })

2)     Inject as ‘local service’

To inject as local service, inject the service into component directly.
See the following code inside the Service-Component.component.ts file.

import { Component, OnInit } from '@angular/core';
import { MyServiceService } from '../services/Myservice.service'; 
  selector: 'app-service-component',
  templateUrl: './ service-component.component.html',
  styleUrls: ['./ service-component.component.css'],
  providers: [MyServiceService]
export class ServiceComponentComponent implements OnInit{
  constructor(private myservice: MyserviceService){  }
     this.todaydate = this.myservice.showTodayDate();
     this.msg = this.myservice.serviceproperty;   

So, we can register the service in Angular, either locally or globally.
If you are using services on more than one component, then you should define one global, and otherwise, local works just fine. It depends on the size of the project.