[
{ path: '', redirectTo: '/myApp/home(secondary:xyz)', pathMatch: 'full' },
{ path: 'myApp'
children: [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', ... },
...
{ path: 'product'
children: [
{ path: '', redirectTo: 'categoryA', pathMatch: 'full' },
{ path: 'categoryA', component: CategoryAComponent, canActivate: [CategoryACanActivateGuard]},
{ path: 'categoryB', component: CategoryBComponent},
...
]
},
...
]
},
...
]
Now, I want to control the access to www.myWeb.com/myApp/product/categoryA. If the user doesn't have enough permission, he/she will be redirected to ... /product/CategoryB. I have written a CanActivate RouteGuard to do this, the guard class looks like this:
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, ActivatedRoute } from '@angular/router';
import { MyService } from '... my-service.service';
@Injectable()
export class CategoryACanActivateGuard implements CanActivate {
constructor(private myService: MyService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise {
return this.myService.checkPermission()
.then(result => {
if (!result.hasAccess) {
//redirect here
this.router.navigate(['./myApp/product/categoryB']);
//works, but I want to remove hardcoding 'myApp'
//this.router.navigate(['../../categoryB']);
//doesn't work, redirects to home page
//this.router.navigate(['./categoryB'], { relativeTo: this.route});
//do not have this.route object. Injecting Activated route in the constructor did not solve the problem
}
return result.hasAccess;
});
}
}
Everything works fine, but I want redirect relative to the target route like the following:
this.router.navigate(['/product/categoryB'], { relativeTo: });
// or
this.router.navigate(['/categoryB'], { relativeTo: });
Unfortunately, relativeTo accepts only ActivatedRoute objects and all I have is ActivatedRouteSnapshot and RouterStateSnapshot. Is there a way to navigate relative to the target route (in this case categoryA)? Any help will be really appreciated.
Note:
* I can not change the route configuration other than adding some route-guards.
* I am not looking looking for this.router.navigateByUrl using state.url. I want to use router.navigate([...], { relativeTo: this-is-what-need}).
0 comments:
Post a Comment
Thanks