Sharing Data with Services

Tutorial 4 of 5

Sharing Data with Services in Angular

1. Introduction

In this tutorial, we will learn how to use Angular Services to share data across components. Data sharing is a common necessity in web applications, and Angular Services provide an efficient way to achieve this.

By the end of this tutorial, you will be able to:

  • Understand the concept of Angular Services
  • Create and use Angular Services to share data across components

Prerequisites:

Before starting this tutorial, you should have a basic understanding of:

  • Angular
  • TypeScript
  • Angular CLI

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 not refreshed and is persistent.

Here is how you can create and use a service to share data in Angular:

  1. Create a Service: Use Angular CLI to generate a service.

    ng generate service DataService
    This command generates a service named DataService.

  2. Implement Data Sharing Method: Inside data.service.ts, implement a method to share data.

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

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

    setData(id: number, data: string) {
    this.data[id] = data;
    }

    getData(id: number) {
    return this.data[id];
    }
    }
    `` This service hassetDataandgetData` methods to set and get data respectively.

  3. Inject and Use the Service: Inject this service in any component and use it to share data.

    ```typescript
    import { DataService } from './data.service';

    export class AppComponent {
    constructor(private dataService: DataService) {}

    setData() {
    this.dataService.setData(1, 'This is some data');
    }

    getData() {
    console.log(this.dataService.getData(1));
    }
    }
    ```

    setData and getData methods are used to set and get data.

3. Code Examples

Example 1: Sharing Data Between Two Components

// data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message);
  }
}

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

@Component({
  selector: 'app-component1',
  template: `
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./component1.component.css']
})
export class Component1Component {

  constructor(private data: DataService) { }

  newMessage() {
    this.data.changeMessage("Hello from Component 1");
  }
}

// component2.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-component2',
  template: `
    {{message}}
  `,
  styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message);
  }
}

The DataService holds the data, Component1Component sets the data, and Component2Component gets the data.

4. Summary

In this tutorial, you learned about Angular Services and how to use them to share data between components. We created a service using Angular CLI, implemented methods to set and get data, and injected the service into a component to share data.

As next steps, you may want to explore more about Angular Dependency Injection, Observables and Subjects, and other advanced Angular topics.

5. Practice Exercises

  1. Exercise 1: Create a service to share data across three different components. Component1 sets the data, Component2 modifies it, and Component3 gets the data.

  2. Exercise 2: Explore BehaviorSubject in Angular and use it in a service to share data.

Tip: BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:

  • It needs an initial value as it must always return a value on subscription even if it hasn't received a next().
  • Upon subscription, it returns the last value of the subject. A regular observable only triggers when it receives an onNext.
  • At any point, you can retrieve the last value of the subject in a non-observable code using the getValue() method.

Unique features of a subject compared to an observable are:

  • It is an observer in addition to being an observable so you can also send values to a subject in addition to subscribing to it.

In addition, you can get an observable from behavior subject using the asObservable() method on BehaviorSubject.

Solution: A basic solution has been shown in Code Examples section. Try to modify it according to the requirements of the exercises.