I am currently working in Angular 4 with sibling components, where there are no parent-child relationships, only siblings.
One of the siblings is able to successfully retrieve data, particularly the ID from the URL using the code snippet below:
public getId () {
const id = +this.route.snapshot.paramMap.get('id');
// console.log (id); //working!
return id
}
However, the other sibling attempted to do the same but could not retrieve the ID, even though they are on the same route. The reason for this remains a mystery to me.
My solution was to pass the ID from one sibling component to the other. After researching, I found examples for passing data between parent and child components but not between siblings. It seems that using a service to pass the data is the best approach, following this tutorial.
Despite my efforts, something doesn't seem to be working correctly. So, where exactly is the issue?
Component one: This component is responsible for fetching the ID from the URL.
urlId: number;
public getId () {
const id = +this.route.snapshot.paramMap.get('id');
// console.log (id); //working!
return id
}
ngOnInit(): void {
const id = +this.getId ();
this.taskService.newId(id)
}
The service: This service updates the 'noId' variable using the function newID().
private noId = new BehaviorSubject<number>(0);
defaultId = this.noId.asObservable();
newId(urlId: number) {
this.noId.next(urlId);
console.log (urlId); // this still working
}
Component two: This component should receive the data after running the ngOnInit() function, but nothing is happening.
urlId: number;
ngOnInit() {
this.taskService.defaultId.subscribe(urlId => this.urlId = urlId)
console.log (this.urlId); //return 0, or the same value as private noId
}
Unfortunately, Component 2 is not receiving updated data. What could be causing this issue?