1

For now I'm using angular2 rc.4. But in near future I will update my app to rc.6.

My task is to determine active route, I want to implement route guard by user role/type/whatever on backoffice.

One my app is open for all users, and another app is backoffice.

some of backoffice's routes:

{
    path: "proposal",
    component: ProposalCmp,
    data: {
        authList: [
            ROLES_DATA.ADMIN,
        ]
    }
},
{
    path: "proposal/:id",
    component: ProposalCmp,
    data: {
        authList: [
            ROLES_DATA.ADMIN,
            ROLES_DATA.CUSTOMER
        ]
    }
},

On application initialization stage routes are filtered by authList roles to prevent showing all links on dynamic menu. If some type of user shouldn't see it, it isn't shown and it works fine.

But on first loading (reloading the page) I've faced some issues. For example if I logged in as customer only proposal/:id can be viewed but also proposal.

So I've decided to write route guard:

@Injectable()
export class RouteGuard implements CanActivate {
    constructor(private tokenService: TokenService,
                private router: Router,
                private activatedRoute: ActivatedRoute) {
    }

    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
        // this.router.isActive(url=string|UrlTree, exact=true)
        // released in rc.5 - https://github.com/angular/angular/blob/2.0.0-rc.5/modules/%40angular/router/src/router.ts#L328
        console.log(state.url, this.router.url);

        return true;
    }
}

In the end, at the first page load (reloading the page) I can get correct url only from state.url, route object seems initialized by default values, route.data is empty as route.url.

If app is loaded and another route is activated, by clicking on a link for example, I will get correct route.data in canActive() method.

Well, ok, I can import the array of all my routes and go through them, but how can I parse route path proposal/:id and compare it with proposal/6 which I can get from state.url? It is good that I have not used yet aux but what if I will. I can use regexp for now but I don't think it's a good option for future.

I found similar problem - Angular 2 routes current url with params

Questions are:

  • Why I can't get current activated route snapshot on app loading and how can I detect it? ActivatedRoute.url.subscribe() or other subscriptions don't work.
  • How can I compare proposal/6 from state.url with proposal/:id from my route path in the right way?
  • Or may be there are another options how can I detect active route, or even another solution?
Community
  • 1
  • 1
Andrei Shostik
  • 342
  • 1
  • 4
  • 17

0 Answers0