Angular: Setup routes depending on service method call

末鹿安然 提交于 2019-12-05 04:31:01
Taras Ilyin

If I correctly understood your problem, I think you probably can consider using route guards to reach you goal. I suggest you to use guards feature to specify the conditions of accessing your routes, instead of changing the list of routes.

Please check this link for more information about route guards:

https://codecraft.tv/courses/angular/routing/router-guards/

I hope this will help you.

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { YourSecurityService } from './your-security.service';

@Injectable()
export class YourRouteGuardService implements CanActivate {

    constructor(
        private router: Router, 
        private yourSecurityService: YourSecurityService) {
    }

    canActivate(
        route: ActivatedRouteSnapshot, 
        state: RouterStateSnapshot): boolean {

        console.log(state.url); // HERE YOU CAN GET REQUESTED ROUTE

        if (this.yourSecurityService.checkIfUserHaveAccess())
            return true;

        this.router.navigate(['your-route-to-redirect']);
        return false;
    }
 }

Next you should apply your guard to your route:

const appRoutes: Routes = [
    {
        path: 'someroute',
        component: RouteComponent,
        canActivate: [YourRouteGuardService]
    },
    ...
]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!