Guard尝试重定向到另一个页面时引发错误

时间:2019-03-24 04:08:10

标签: angular

我试图让AuthGuard重定向用户登录到未授权页面。 但是它每次都失败,我不知道为什么。

错误消息:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'unauthorized'
Error: Cannot match any routes. URL Segment: 'unauthorized'

app.component.html

<router-outlet *ngIf="isAuthenticated()"></router-outlet>
<router-outlet *ngIf="!isAuthenticated()" name="public"></router-outlet>

auth.guard.ts

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router, private authServ: AuthService ) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.checkUser(route, state);
  }

  private checkUser(route: any, state: any): boolean {
    console.log('AuthorizationGuard is hit');

    if(!this.authServ.isAuthorized()) {
            this.router.navigate(['/unauthorized']);
            return false;
    } else {
            return true;
    }
  }
}

我的app.routing.module路由定义如下:

  { path: 'dashboard', component: MainDashboardComponent, canActivate: [AuthGuard] },
  { path: 'unauthorized', component: UnauthorizedComponent, outlet: 'public'},
  { path: '', component: HomeComponent, outlet: 'public'}

任何建议都值得赞赏。 我怀疑这个问题与命名插座有关,因为当我不使用它时,它似乎没有发生。

2 个答案:

答案 0 :(得分:1)

辅助出口的语法不同,您需要定义对象是链接数组参数的frst参数

尝试一下

private checkUser(route: any, state: any): boolean {
    console.log('AuthorizationGuard is hit');

    if(!this.authServ.isAuthorized()) {
            this.router.navigate([{outlets:{public:['unauthorized']}}]);
            return false;
    } else {
            return true;
    }

答案 1 :(得分:0)

您添加了未经授权的路径来公开销售渠道,因此这种情况正在发生。 您可以从app.routing.module.ts

中删除插座选项
  { path: 'unauthorized', component: UnauthorizedComponent, outlet: 'public'},

收件人:

  { path: 'unauthorized', component: UnauthorizedComponent },

和html

<router-outlet *ngIf="isAuthenticated()"></router-outlet>
<router-outlet *ngIf="!isAuthenticated()" name="public"></router-outlet>

收件人

<router-outlet></router-outlet>