Angular / Angular Services and Dependency Injection

Sharing Data with Services

This tutorial will explain how to use Angular Services to share data across components. Data sharing is a common requirement in many applications, and Services provide an efficien…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explains creating services and using dependency injection in Angular.

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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help