Вы можете создать AuthGuard, как показано ниже:
import { Injectable } from "@angular/core";
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import "rxjs/add/operator/toPromise";
import { AuthService } from "./auth.service";
import { User } from "models/user.model";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const isLoggedIn = this.authService.isLoggedIn;
const currentUser: User = this.authService.currentUser;
if (isLoggedIn == true && currentUser != null) {
// check if route is restricted by role
const roles = route.data.roles;
if (roles) {
const userRolesValid: boolean = this.authService.validateUserRoles(roles);
if (userRolesValid == false) {
// role not authorised so redirect to home page
this.router.navigate(["/"]);
return false;
}
}
return true;
}
// not logged in so redirect to login page with the return url
this.authService.logout();
this.router.navigate(["/login"], { queryParams: { returnUrl: state.url } });
return false;
}
}
Затем вам нужно добавить свойство AuthGuard as canActivate ко всем маршрутам приложения, для которых вы хотите проверить это:
{ path: "home", component: HomeComponent, canActivate: [AuthGuard]}
Пожалуйста, не забудьте также импортировать AuthGuard в качестве провайдера в файл app.modules
import { AuthGuard } from "services/auth.guard";
@NgModule({
providers: [ AuthGuard ]
})