Angular 2 Auth Guard重定向到主页

时间:2017-03-15 13:19:05

标签: angular typescript

如果路由被AuthGuard阻止,是否有办法重定向到我的主页。

例如,如果用户在未登录的情况下访问www.my-example.com/user,他将被auth guard阻止,我希望该用户被重定向回主页。目前它只显示一个空白页面。

// app.routing.ts
const APP_ROUTE: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full', },
{ path: '', component: UserLayoutComponent, children: [
    { path: 'user', loadChildren: 'app/user/user.module#CalenderModule' },
    ]
}];

// user.routing.ts
const USERR_ROUTE: Routes = [
    { path: '', component: UserComponent, canActivate: [AuthGuard] },
];

export const userRouting = RouterModule.forChild(USERR_ROUTE);

1 个答案:

答案 0 :(得分:2)

import{Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';

@Injectable()
export class  AutoGuard implements CanActivate{
  constructor(private _router : Router){}
  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    if(/*some condition*/){
        this._router.navigate(['/some_url']);
        return false;
    }
    return true;
  }

}