I have two sibling components and I want to share the data between them. For the user's convenience, if the UI on component one changed then I want to emit the inform the component two. Then the component two's UI should change by the passed parameter.
Vice versa if the component two's UI change I also want to inform component one as well. So I used Behavior subject to share the data.
However it causes the circular calling.
Stackblize BehaviorSubject demo
The BehaviorSubject
is in the service class.
import { Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
@Injectable()
export class UsersService{
constructor(){}
private user = new BehaviorSubject<number>(0);
public getUser = (): Observable<number> => {
return this.user.asObservable();
}
public editUser = (newUser: number) => {
this.user.next(newUser);
}
}
So we have get and set part. In the sibling components we call get user part in ngOninit
.
ngOnInit(){
this.userService.getUser().subscribe(u => {
if(u > 0) {
this.patchData(u);
this.newUser = u + 1;
console.log(u);
}
});
}
Once we get the user number then we emit so the other component can receive it and render the UI afterwards.
The error is shown in console.