How to share data between not related component in angular.

Shail Gandhi
2 min readFeb 19, 2022

--

We already know that@Input() and @Output() decoratives are used for sharing the data between child and parent components but what if components are not related to each other then ?

Here we are going to show how we can share data between two components, For that we are using “Subject” rxjs.

Subject” is a special observable which is use for multicasting and it is implimented in service class of angular by importing from rxjs and create the object of it, like below example.

/** Service.ts file **/
...
...
import { Subject } from ‘rxjs’; // Import@Injectable({
providedIn: 'root'
})
export class UserService {
...
...
transferData = new Subject(); // create object...
...
}

Now we can import service in some component.ts file and create the instance of it.

Now for multicast the data I have bind a click event on button in component.html file which is called method of component.ts file and from that function data will multicast through instance of subject observer which is available in service. See below code

/** component.ts file (send the data) **/multicast(component:string, message:string) {
this.userservice.transferData.next({‘component’:component, ‘message’:message})
}

In above function we called “transferData” instance of subject observer and use “.next” method with data as argument.

At other side if you want to receive multicasted data to another component then we need to use “.subscribe” method. See below code

/** parent.component.ts file (receive the data) **/ngOnInit() {
this.receiveMulticastData(); // must be called from ngOnInit
}
receiveMulticastData():void {
this.userservice.transferData.subscribe((res: any) => {
if(res.component == "parent") {
this.childMessage = res.message;
}
});
}

Finally it will give you output as below

We did it…..

You can download the source code from below url
https://github.com/virusweb/angular-demo

--

--