Angular Services

Angular Services

Angular Services

In this tutorial, we are going to learn more about angular services.

Services are great way to share or store piece of information among different components of angular application.
Services can easily be injected to other services or components.

How to create a Service ?

Let’s look how to create a service class in angular.

Creating a service in angular is easy, you can run the below CLI command to create a new service.

ng generate service service-name

@Injectable() – Decorator which makes the service class eligible or participates in the dependency injection system.

You must make the service available to dependency injection system
before angular can inject it.

proviteIn : ‘root’ – provide the service at the root level (AppModule). A single shared instance is created and injected into any class that asks for it.

Hierarchy of Service Injector


AppModule – If you provide service into app module (using providers), the same instance will be available application-wide.
AppComponent – If you provide service into app component, the service will be available for all the components but not for other services.
Components – If you provide service into components then the service will be available for that component and to all it’s child components.


Let’s take a look below and see the directory structure of our component.

Angular Services
Angular Services

Creating the user component

To understand angular services better, let’s create a user component. We will create user service and inject it to user component later.

You can create user component by the following CLI command.

ng g c service-test/components/user-component

Above command will create you component automatically and add it to the app module.

Creating the user service

Now let’s create user service. User service will hold some user names as an array. We will create two public methods to get the users list and add some users from the components.

You can create a new service with the following CLI command.

ng g service service-test/services/user-service

Above command will create the user service class and will automatically register it as singleton (provideIn: ‘root’). Below is the service class.

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

@Injectable({
   providedIn: ‘root’
})
export class UserServiceService {
   private userNames : string[] = [];

   constructor() {
     this.userNames.push(‘bob’);
     this.userNames.push(‘john’);
     this.userNames.push(‘danny’);
}

public getUserNames() : any {
     return this.userNames;
}

public addUser(name: string) {
     this.userNames.push(name);
}

}

Injecting Service into Component


When service is ready, we can now inject it to our components. Since, our service is added at root level so it will be available to all components as shared service. We can simply inject it from constructor itself.

User Component

import { Component, OnInit } from ‘@angular/core’;
import { UserServiceService } from ‘../../services/user-service.service’;

@Component({
   selector: ‘app-user-component’,
   templateUrl: ‘./user-component.component.html’,
   styleUrls: [‘./user-component.component.css’]
})
export class UserComponentComponent implements OnInit {
public userNames: string[];
public user = {name : };

constructor(private userService: UserServiceService) { }

ngOnInit() {
     this.userNames = this.userService.getUserNames();
}

public addName() {
     this.userService.addUser(this.user.name);
}

}

User Component Template

<div class=“row” style=margin-top: 20px”>
  <div class=“col-md-4”>
    <div class=“card”>
      <div class=“card-header”>User Names</div>
      <div class=“card-body”>
          <div class=“row” style=margin-bottom: 20px”>
             <div class=“col-md-9”><input type=“text” name=“user.name” [(ngModel)]=“user.name” class=“form-control” /></div>
             <div class=“col-md-3”><button class=“btn btn-primary” (click)=“addName()”>Add</button>    </div>
</div>
<ul class=“list-group”>
<li class=“list-group-item” *ngFor=“let name of userNames”>{{name}}</li>
</ul>
</div>
</div>
</div>
</div>


You will see the results as below.

Angular Services

Related Post

Leave a Reply

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