8. Services

For data or logic that isn’t associated with a specific view, and that you want to share across components, you create a service class. A service class definition is immediately preceded by the @Injectable() decorator. The decorator provides the metadata that allows other providers to be injected as dependencies into your class.

A component can delegate certain tasks to services, such as fetching data from the server, validating user input, or logging directly to the console. By defining such processing tasks in an injectable service class, you make those tasks available to any component. You can also make your application more adaptable by injecting different providers of the same kind of service, as appropriate in different circumstances.

Creating a service using CLI

Run the ng generate service <service-name> command, where <service-name> is the name of your service.

This creates the following files:

The created service file(my.service.ts) looks like this:

import { Injectable } from ‘@angular/core’;

@Injectable({

  providedIn: ‘root’,

})

export class MyService {

  constructor() { }

}

Dependency injection

When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the constructor parameter types. For example, the constructor of MyListComponent needs MyService.

export class MyListComponent {

 constructor(private service: MyService) { }

}

We need to inject the MyService in the MyListComponent using the constructor in order to use the service for communication.

Component communication using services

Now let us see how to set up communication between components using services.

First let us create two components using the ng generate command:

ng generate component first

ng generate component second

This creates two components as follows:

Now, create a service using the ng generate command:

ng generate service my

This will create a service named MyService

import { Injectable } from ‘@angular/core’;

@Injectable({

  providedIn: ‘root’,

})

export class MyService {

  constructor() { }

}

Now let us try to send some data from the FirstComponent to the SecondComponent which we created earlier.

First, we create a property in the FirstComponent as follows:

import { Component } from ‘@angular/core’;

@Component({

  selector: ‘app-first’,

  templateUrl: ‘./first.component.html’,

  styleUrls: [‘./first.component.css’]

})

export class FirstComponent {

  data1 = “edupoly”;

}

Next, we need to send this data to the service, which can later be sent to the SecondComponent.

To use the service to store this data, we have to inject the service in the FirstComponent with the help of the constructor as follows:

import { Component } from ‘@angular/core’;

import { MyService } from ‘../my.service’;

@Component({

  selector: ‘app-first’,

  templateUrl: ‘./first.component.html’,

  styleUrls: [‘./first.component.css’]

})

export class FirstComponent {

  data1 = “edupoly”;

  constructor(private myService:MyService){

  }

}

Now, we need to create a property in the service where we will store the data from the FirstComponent.

import { Injectable } from ‘@angular/core’;

@Injectable({

  providedIn: ‘root’

})

export class MyService {

  data:any;

  constructor() { }

}

Next, let us store the data of the FirstComponent in the property of the MyService  as follows:

import { Component } from ‘@angular/core’;

import { MyService } from ‘../my.service’;

@Component({

  selector: ‘app-first’,

  templateUrl: ‘./first.component.html’,

  styleUrls: [‘./first.component.css’]

})

export class FirstComponent {

  data1 = “edupoly”;

  constructor(private myService:MyService){

    this.myService.data = this.data1;

  }

}

Now, we can access this data in our SecondComponent by accessing the service by injecting it in a similar manner as follows:

import { Component } from ‘@angular/core’;

import { MyService } from ‘../my.service’;

@Component({

  selector: ‘app-second’,

  templateUrl: ‘./second.component.html’,

  styleUrls: [‘./second.component.css’]

})

export class SecondComponent {

  data2:any;

  constructor(private myService:MyService){

    this.data2 = this.myService.data;

  }

}

The received data can be displayed in the template of SecondComponent by using interpolation.

<p>{{data2}}</p>

Quiz:

What is a service in Angular?

a. A module for organizing components

b. A class that provides a specific functionality

c. An Angular directive

d. A decorator for styling components

Which decorator is used to mark a class as an injectable service in Angular?

a. @Component

b. @Directive

c. @Injectable

d. @Service

What is dependency injection in Angular?

a. A way to inject dependencies into a component

b. A technique to create circular dependencies between components

c. A method to add external libraries to an Angular project

d. A process to eliminate the need for services in Angular

How do you inject a service into a component in Angular?

a. Using the @Inject decorator

b. Using the @Injectable decorator

c. Using the constructor of the component

d. Using the @Component decorator

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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