Communicate between Angular components
Nicolas LARRODE
Posted on August 25, 2020
Angular v10.0.9
The first time I had to communicate between two Angular components, it was Parent/child relation, and it's pretty easy with @output and @input.
But the first time I had to, without this relation, I was completely lost.
Create a Service
We assume you have now two components, not connected by any relationship, let's create a new service :
ng g service <name>
name it like you want !
The generated Service looks like :
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
// Your code here
}
Subject
We will use Subject, a special type of Observable that allows values to be multicasted to many Observers !
Import Subject from rxjs in your Service :
import { Subject } from 'rxjs'
Now we can create a Subject to carry the data to share between our components :
data: Subject<Type> = new Subject();
Subject can be any Typescript type
It's Done !
Yeah, really.
You have just to import the service into your components with :
import { dataService } from "../services/data.service";
+
constructor(
private sharedData: dataService,
) {}
To get the data
this.sharedData.data.subscribe(data => {
//Do what you want with data
})
data will be updated automatically
To set the data :
this.sharedData.data.next(newValue)
The data will be updated in ALL your components wich have subscribed to the value
Thanks for reading! Was this article helpful for you? Any ideas that can be shared? Post a comment below!
P.S. This is my first Angular post, I hope you will love it !
Posted on August 25, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.