Services in Angular

services in angular

A ‘Service’ in Angular is a class intended to perform a specific task. Generally, we create services in Angular based on our objective. Each and every objective will have its own service.

Let’s take an example of a simple mathematical operation: Sum of two values should be logged in the output.

In order to perform this, we need to write the logic to do the arithmetic operation and based on the logic, we can see the result in the output.

But,

The location where are we writing this logic i.e. in which file makes a considerable difference as explained below.

In general, we write the code inside the ‘component’ and it works fine. But, the actual purpose of a component is mediating between the ‘application logic’ and ‘view’. It aids in providing the methods and properties to data binding.

So, to make the component’s job easy, we divide the tasks and create separate ‘services’ in Angular for individual tasks. In addition to this, we can even use these services in multiple components when required, by which we can eliminate the code duplication.

How do we use services in Angular?

  1. To share the data across multiple components.
  2. To implement application logic.
  3. For external interactions like connecting to database.

Now, How to use a service inside a component?

As we are creating multiple services in Angular based on our objectives, we should integrate such services with the component. That means we make the service available for the component to interact with it.

We will see the step by step process of service creation and it’s integration below.

Service creation in Angular

To create a service, run the command below in the terminal.

 $ ng g s ServieName

Or

$ ng generate service ServiceName

By running this command, service will be created. A screenshot below shows the default file it generates.

Services in Angular

‘@Injectable’ decorator has provider ‘ProvidedIn’ helps in making this service available everywhere or for a specific component as well.

By default it will be ‘root’ and that indicates it is available to use across the application.

In case, if we want to make this service available for all the components inside a specific ‘Module’, we have ‘providers’ property to integrate it with.

Below is the example from @angular.io which demonstrates the usage of NgModule with providers.

@NgModule({
  providers: [
  BackendService,
  Logger
 ],
 ...
})

© Angular.io

If we want to do it in the ‘Component’ level, we use ‘providers’ section in respective ‘Component.ts’ file. For syntax check the code below.

@Component({
  selector:    '',
  templateUrl: '',
  providers:  [ Servicename]
})

© Angular.io

In the above example, inside ‘Component’, we can see the ‘Servicename’ integrated using ‘providers’. So, this ‘Component’ can access the service we have added using ‘providers’.

Let’s look at an example of how to get ‘form data’ from a component to service.

Store ‘Form data’  using a service in Angular

Go to the ‘html component’ file and develop a form with the required fields using ‘form’ tag. If we want to set validation to the ‘form fields’ check the example below.

<form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputName">Name</label>
<input type="name" class="form-control" name="name" [(ngModel)]="model.name" #name="ngModel" [ngClass]="{ 'is-invalid': f.submitted && name.invalid }" required placeholder="Digital Brolly">
</div>
<div class="form-group col-md-6">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" name="email" [(ngModel)]="model.email" #email="ngModel" [ngClass]="{ 'is-invalid': f.submitted && email.invalid }" required email placeholder="digitalbrolly@gmail.com">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress2">Phone Number</label>
<input type="tel" class="form-control" name="number" [(ngModel)]="model.number" #number="ngModel" [ngClass]="{ 'is-invalid': f.submitted && number.invalid }" required placeholder="+91 9696963446">
</div>
<div class="form-group col-md-6">
<label for="inputService">Service</label>
<select class="custom-select mr-sm-2" name="service" [(ngModel)]="model.service" #service="ngModel" [ngClass]="{ 'is-invalid': f.submitted && service.invalid }" required>
<option selected>Choose...</option>
<option value="SEO">SEO</option>
<option value="SMM">SMM</option>
<option value="Google Ads">Google Ads</option>
<option value="SEO & SMM">SEO & SMM</option>
<option value="SMM & Googel Ads">SMM & Googel Ads</option>
<option value="Web Dev & Designing">Web Dev & Designing</option>
<option value="Custom">Custom</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputMessage">Your Note</label>
<textarea class="form-control" name="note" [(ngModel)]="model.note" #note="ngModel" placeholder="Looking to outsource our website SEO."></textarea>
</div>
<button type="submit" class="btn btn-outline-dark">Send Request</button>
</form>
[(ngModel)]

I am using ngModel here to hold the data entered by users in the form fields

[ngClass]

‘ngClass’ helps to implement the conditional validation to the form fields. When user submits the form it will check for all the ‘form fields’ conditions inside the ‘ngClass’ and see if all the conditions are met then only it sends the data.

(ngSubmit)="f.form.valid && onSubmit()"

(ngSubmit) which is added to the form tag initiates this whole process soon after the submit button got triggered.

If you observe the value passed to ngSubmit we have two values with ‘&&’ symbol as separator. The first one ‘f.form.valid’ is for validating the form fields and the second ‘onSubmit()’ function to store the data after successful submission.

Create a Global Service

Now, we create one global service and import the dependencies required to handle the HTTP request.

With the syntax mention at the start of the article, we can create a service with the name of wish.

Once the ‘service.ts’ file got created we need to import ‘httpClient’ and ‘httpHeaders’ into this service file.

import{HttpClient,HttpHeaders} from '@angular/common/http'

Then create a constructor to use ‘httpClient’.

constructor(private http:HttpClient) { }

Now, declare put(), get(), post() and delete() methods. Here you will understand the actual advantage of having service in angular.

export class Service {
 
 
  constructor(private http:HttpClient) { }
 
  
  public put() {
    
  }
 
 public  get(bundle) {
     return this.http.get("dfdf")
 }
 
  
  public post() {
    
  }
 
 public delete() {
   
 }
 
}

We have created a service file separately and written the code snippets required to capture the ‘form’ values from ‘form’ using ‘get()’ method. This is a one-time setup for an application. From now onwards wherever required we simply inject this service into the respective file and use it directly instead of writing it again and again.

As a next step, try to create one more service inside the component folder where we have written the ‘form’ code and open that service file and import the global service to use it here.

import { Service } from '../../Shared/service';

Note: Don’t forget to change the path in the above line as per folder structure.

Also, import ‘httpClientModule’ & ‘HttpClient’

import { HttpClientModule, HttpClient } from '@angular/common/http';

Now, create a constructor to use the global service we created before in this local service file.

constructor(private httpservice:Service) {
 
   }

Here, ‘Service’ is the name of the global service we have created. 

savedata(Homeobj:any)
   {
   return this.httpservice.get({formData:Homeobj})
   }

Using ‘savedata(Homeobj:any)’ I am getting the form values into ‘Homeobj’ and then I assigned it ‘formData’. Now, we have the data stored in ‘formData’.

But, how this ‘savedata’ got ‘form fields’ info from component?

Here is how?

Come back to the html component where we have written the form code with ‘onSubmit()’ as it’s where it all started.

We need to head over to ‘TypeScript’ file of this component and write the logic which has to be executed when onSubmit() got called.

Here is the piece of code we need to put it on ‘ts’ file.

onSubmit() {
    let  data=this.model;
    this.homeservice.savedata(data,1,2,3).toPromise().then(res=>{
     
    })
 

To make this code work, we need to import the local service into this ‘ts’ file.

import {HomeregService} from './homereg.service';

‘Homeregservice’ is the name of my local service. The complete file looks like this.

import { Component, OnInit } from '@angular/core';
import {HomeregService} from './homereg.service';
 
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
 
  model: any = {};
  angService: any;
  constructor(private homeservice:HomeregService) {
 
  }
  ngOnInit() {
  }
  onSubmit() {
    let  data=this.model;
    this.homeservice.savedata(data).toPromise().then(res=>{
     
      })
  }
}

With this, we are getting form data to the component on successful submission (from html to ts).

Conclusion of Angular Services:

At first, ‘form data’ will get stored inside the component (ts file from html), then it will be transferred to the local service with the help of global service. For there, we can send the data to backend by converting this into the required format (JSON Object, XML etc) that backend team ask for.

Angular Services- FAQS

What are services in angular?

Services in Angular are to share data across multiple components and these services will help to reuse the application logic instead of duplicating the code wherever require.

How do I write a service in angular?

Import the dependencies, create a service using ng g s ServieName and make this service available across multiple components using providers and use the service.

What is angular in simple terms?

A JavaScript framework helps to develop a Single page application (Loads the body portion of the page instead of reloading the complete page) and maintain them with an easy.

How angular services work?

In angular, any global service can be injected into a component based on the requirement by using dependency injection through which we can make use of a particular service inside the component.

Check out my article on data binding in Angular

6 comments on “Services in Angular

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to learn Facebook Ads for FREE?Subscribe now to get FREE access to Facebook Ads Course