Intro to Services in Angular

Intro to Services in Angular

In this tutorial, we will learn about how to create and use services in angular with the help of examples.

What is a Service?

A service is a class which holds the data or functions that our application needs, which helps us to store our application logic in a separate file so that we can reuse the service with different components.

Creating a service

Open your terminal and run the following command to create a service.

ng generate service clickscount
#clickscount is our service name

This above command will generate two new files in your app directory clickscount.service.ts and clickscount.service.spec.ts.

clickscount.service.ts: This is the file we use to create our service.

clickscount.service.spec.ts: It is used for testing purposes.

Let’s open our clickscount.service.ts file.

clickscount.service.ts
import { Injectable } from '@angular/core';
@Injectable({  providedIn: 'root'})export class ClickscountService {

  constructor() { }
}

This is the code angular generates by default let’s discuss the code we see above.

@Injectable is a decorator which accepts the object as its first argument inside that object we have a providedIn property with value root it means we are telling angular to create a single shared instance of the ClickscountService and injects it to any class we ask for it.

Now we are going to add some logic to our ClickscountService so that we can use it in our components to count our button clicks.

Update your clickscount.service.ts with below code.

clickscount.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ClickscountService {
  count = 0;
  constructor() { }

  increment() {
    this.count++;
  }

}

Using the service

Let’s use the ClickcountService inside our AppComponent to count the button clicks.

app.component.ts
import { Component} from '@angular/core';
import { ClickscountService } from './clickscount.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent{

  constructor(private clicksCount: ClickscountService) {  }

  handleClick() {    this.clicksCount.increment();  }}

In the above code, first, we imported the ClicksCountService from ./clickscount.service.ts file and we added to the constructor private clicksCount: ClickscountService it tells angular to inject the ClickscountService to this component.

app.component.html
<div style="text-align:center">
  <h1>No of clicks {{clicksCount.count}}</h1>  <button (click)="handleClick()">Click me</button>
</div>

Problems

Currently, we have a problem if we try to use our ClicksCountService in other components the same instance shared among all components so that we can a get wrong click count.

To solve this problem we can also inject a service instance in the component level instead of injecting at the root level.

Now update your clickscount.service.ts file by removing @Injectable decorator.

clickscount.service.ts
export class ClickscountService {
  count = 0;
  constructor() { }

  increment() {
    this.count++;
  }

}

Injecting the service in component level

app.component.ts
import { Component } from '@angular/core';
import { ClickscountService } from './clickscount.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ClickscountService] //  injecting component level})
export class AppComponent {
  constructor(private clicksCount: ClickscountService) {
  }

  handleClick() {
    this.clicksCount.increment();
  }
}

In the above code we have updated our AppComponent by adding a providers array with value ClickscountService so that its tells angular to inject the Clickscountservice instance in AppComponent.

Code repository