From my understanding, in Angular 2, if you want to pass values between unrelated components (i.e., components that don't share a route and thus don't share a parent-child relationship), you do so via a shared service.
So that's what I've set up in my Angular2 app. I am checking to see if a certain series of characters exist in a url and returning true if it does.
isRoomRoute(routeUrl) {
if ((routeUrl.includes('staff') || routeUrl.includes('contractors'))) {
console.log('This url: ' + routeUrl + ' is a roomRoute');
return true;
} else {
console.log('This url: ' + routeUrl + ' is NOT a room route');
return false;
}
}
In the constructor of the root app.component, I'm subscribing to routing events:
constructor(private routeService: RouteService,
private router: Router) {
this.router.events.subscribe((route) => {
let routeUrl = route.url;
this.routeService.sendRoute(routeUrl);
this.routeService.isRoomRoute(routeUrl);
});
}
... and then using those provided urls to check whether or not a url contains the specific string. This is evaluated every time the route changes.
So that's all working as expected.
However, I'm running into a problem in passing the result of that check to a different, non-related (non-parent-child) component.
Even though I'm using a shared service (routeService) in both the app.component and the un-related (room.component) component, what works in one doesn't work in the other. From my understanding, the "truthiness" of what's being checked here should be enough to return a true statement.
But in the secondary, unrelated component, I get an "undefined" error when I call the function, like this:
isRoomRoute() {
if (this.routeService.isRoomRoute(this.routeUrl)) {
return true;
}
}
So this is where I'm stuck. Basically the evaluation as to whether a url contains a certain string has already happened. Now I just need to pass the boolean result of that check to the secondary, non-related component. How can I best do this in Angular 2?