Creating and Using Angular Services

Tutorial 1 of 5

Creating and Using Angular Services

1. Introduction

In this tutorial, we will learn how to create and use Angular Services. Angular Services are a crucial part of Angular applications. They help to share data and functionality across components maintaining modularity and efficiency.

You will learn:

  • How to create Angular Services
  • How to inject these services into components
  • How to use services to share data and functionality

Prerequisites:

A basic understanding of Angular and TypeScript is required.

2. Step-by-Step Guide

Angular services are singleton objects that get instantiated only once during the lifetime of an application. They contain methods that maintain data throughout the life of an application, i.e., data is persistent.

Creating a Service

We can create an Angular service using Angular CLI command:

ng generate service data

This command creates a service named data in a file data.service.ts.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class DataService {
  constructor() { }
}

This is a basic structure of a service. The @Injectable decorator tells Angular that this service might itself have injected dependencies.

Using a Service

To use a service, you must first import it and then inject it into the component's constructor.

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private dataService: DataService) { }
}

In this example, DataService is injected into AppComponent. Now, we can use the methods of DataService in AppComponent.

3. Code Examples

Let's extend our DataService to store and retrieve some data.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class DataService {
  private data: string[] = ['Initial data'];

  getData(): string[] {
    return this.data;
  }

  addData(value: string): void {
    this.data.push(value);
  }
}

In this code, we've added a data array and two methods to getData and addData.

Now, let's use this service in our AppComponent.

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private dataService: DataService) { 
    console.log(this.dataService.getData());
    this.dataService.addData('New data');
    console.log(this.dataService.getData());
  }
}

In the app component, we are logging the initial data, adding new data, and then logging the data again.

4. Summary

In this tutorial, we learned how to create Angular Services, how to inject these services into components, and how to use them to share data across an application.

To learn more about Angular Services, refer to the official Angular documentation.

5. Practice Exercises

Exercise 1: Create a service that maintains a count. It should have methods to increment, decrement, and get the count. Use this service in a component and display the count.

Exercise 2: Create a service that fetches data from a REST API using HttpClient. Use this service in a component to display the fetched data.

Solution 1:

Service:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class CountService {
  private count = 0;

  increment(): void {
    this.count++;
  }

  decrement(): void {
    if (this.count > 0) {
      this.count--;
    }
  }

  getCount(): number {
    return this.count;
  }
}

Component:

import { Component } from '@angular/core';
import { CountService } from './count.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  count: number;

  constructor(private countService: CountService) { 
    this.count = this.countService.getCount();
  }

  increment(): void {
    this.countService.increment();
    this.count = this.countService.getCount();
  }

  decrement(): void {
    this.countService.decrement();
    this.count = this.countService.getCount();
  }
}

Keep practicing and exploring more about Angular Services. Happy coding!