You can use singleton services wi th a Subject in order to share data between components (a state management library isn't required).
Create a service using angular-cli : ng generate service service-name
Inject the service into the constructor of the components which need to share the same data :
constructor(private service: MyService) {}
Inside your service, declare a subject which will be responsible to keep the data (a BehaviorSubject is a good idea as it's initialized with a value) :
data: BehaviorSubject<any> = new BehaviorSubject<any>('foo');
To change its value from a component, use the next()
method on it :
constructor(private service: MyService) {}
update(): void {
this.service.data.next('bar');
}
Then in order to get the last value in any component (or service/directive...), subscribe to the BehaviorSubject and do whatever you want with the value :
constructor(private service: MyService) {}
ngOnInit(): void {
this.service.data.subscribe(value => {
// do whatever
});
}
Each time the next()
method will be used somewhere in your application, any subscription somewhere else will get this new value.