In one of my Angular 2 routes\'s templates (FirstComponent) I have a button
first.component.html
One fine solution is to implement a Guard with canActivate method. In this scenario you can fetch data from a given api and let user access the component describe in the routing file. In the meantime one can set the data property of the route object and retrieve it in the component.
Let say you have this routing conf:
const routes: Routes = [
{ path: "/:projectName", component: ProjectComponent, canActivate: [ProjectGuard] }
]`
in your guard file you may have:
canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot)
: Observable | Promise | boolean {
return this.myProjectService.getProject(projectNameFoundElsewhere).pipe(
map((project) => {
if (project) {
next.data = project;
}
return !!project;
}),
);
}`
Then in your component
constructor(private route: ActivatedRoute) {
this.route.data.subscribe((value) => (this.project = value));
}
This way is a bit different than passing via a service since service keep the value in a behaviorSubject as long as it is not unset. Passing via tha guard make the data available for the current route. I havent check if the children routes keep the data or not.