DEV Community

kamran
kamran

Posted on

1

Data Sharing using Services in Angular

Michael started his angular project with two components. He used input decorator to pass data from parent to child component and output decorator to pass data from child to parent component. As the project grew, he kept adding more components to the project and before he knew it, the project was as big as the “Fast and Furious” franchise.
Now his project has a hierarchy of 10 levels and if he wants to pass data from top component to the bottom most, he has to pass the data through all the 10 components. Michael is sad about his work and he knows there is a better way to do this. Lets help him to clean his project.

Michael can use Services to solve this problem and share data between components which are not directly related. So instead of directly passing data from one component to another, we will make a middleware service and use that as a bridge.

We will use Observable to create a Pub-Sub mechanism in a service in our application. Let’s say if component A wants to update a data, it will publish the data to the service and component B wants to get the data value whenever it value is updated then it will subscribe to that data and will receive updates on value change.

I am attaching the Code snippet for publisher, subscriber and the middleware below. I have also created a video tutorial on the same which you can see on the YT channel here.

The middleware where any component can publish and any other component can listen to data updates.

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

@Injectable({
    providedIn: 'root'
})
export class DataServiceService {

    private _dataStream = new BehaviorSubject("");
    constructor() { };

    getDataStream() {
        return this._dataStream.asObservable();
    }

    putDataToStream(data: string) {
        this._dataStream.next(data)
    }

}

Enter fullscreen mode Exit fullscreen mode

This is how component can publish data to the middleware.

import { Component, OnInit } from '@angular/core';
import { DataServiceService } from '../../../../services/data/data-service.service';

import * as categorydata from './category.data.json';

@Component({
    selector: 'app-category',
    templateUrl: './category.component.html',
    styleUrls: ['./category.component.scss']
})
export class CategoryComponent implements OnInit {

    categories: any[] = (categorydata as any).default;
    categoryName: string = "This is Category Component";
    constructor(private dataService: DataServiceService) { }

    ngOnInit(): void { }

    changeVariable(e: string) {
        this.categoryName = e;
    }

    publishData() {
        this.dataService.putDataToStream('Data Published form Category');
    }

}

Enter fullscreen mode Exit fullscreen mode

This is how component can subscribe to the middleware and gets the update.

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { DataServiceService } from '../../services/data/data-service.service';

@Component({
    selector: 'app-card',
    templateUrl: './card.component.html',
    styleUrls: ['./card.component.scss']
})
export class CardComponent implements OnInit {

    @Input() data: any = {};
    @Output() passName = new EventEmitter();
    serviceData: string = "";

    constructor(private dataService: DataServiceService) {
        const data = this.dataService.getDataStream();
        data.subscribe({
            next: (data: string) => {
                this.serviceData = data;
            },
            error: (err: any) => {
                console.log(err);
            }
        })
    }

    ngOnInit(): void { }

}

Enter fullscreen mode Exit fullscreen mode

Thanks for reading, Happy Koding everyone!!!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series