Data Sharing using Services in Angular
Tags: angular, service, javascript, webdev
Published: 2022-07-28 14:03:03

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](https://youtu.be/SEimlo7C-nc).

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)
	}

}

```
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');
	}

}

```
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 { }

}

```

Thanks for reading, Happy Koding everyone!!!