Using angular/router 3.0.0-rc-2, I've been unsuccessful in retrieving data defined on a route from a service that I've created.
I can, however, retrieve the data from within the component defined for that route by injecting ActivatedRoute.
Here is my route:
export const CommonRoutes:RouterConfig = <Route[]>[
{
path: '',
component: Home,
data: {
someKey: true
}
}
];
Here is the implementation that works, but is not the way I want to do this since I need the service to be able to handle this logic:
import {ActivatedRoute} from '@angular/router';
@Component({
//component config...
});
export class Home {
constructor(private _route: ActivatedRoute ) {
this._route.data.subscribe(data => {
console.log(data);
})
}
}
As you might expect, the Home component, when it loads, spits out:
{
someKey: true
}
However, when moving this logic into a service that is injected on the main app component, it logs an empty object.
I have tried subscribing to router navigation events as well, which yields the same difference.
I am wondering if this is more of a paradigm problem. The ActivatedRoute documentation component description says: Contains the information about a component loaded in an outlet. The information is provided through the params, urlSegments, and data observables.
- This leads me to think this will only make the route information available for components linked to a route.
So, I tried another approach- going through the router directly and using Router.routerState. The following is the service class code (which is where I need this logic to happen):
//...truncate imports/injectable decorator....
constructor(private _router:Router) {
this._router.events
.filter(evt => evt instanceof NavigationEnd)
.subscribe(data => {
console.log(_router.routerState.snapshot.root.data);
});
}
This logs, seemingly unexpectedly, and empty object to the console.
Do I have some fundamental misunderstanding of how the router works/should be used? I feel like asking the router for the statically defined data on the current route should be a thing that components should be able to do. But maybe I'm nuts. However, for global logic that depends on a configuration variable that may or may not be present in every single component warrants doing this in a service.
Part of me feels like this kind of over-restrictive design was a flaw in Angular 1, where they prescribed what was "best for you" without taking into account the fact that real world situations don't always dictate the same architecture...
Not sure if it's relevant but I am running this project through webpack.
Any help is appreciated.