0

我有一个带有 AuthGuard 的 SPA。如果使用未记录页面重定向错误页面,则重定向特定路由。现在。

  1. 用户未登录
  2. 呼叫/dashboardAuthgurad重定向/error?returnUrl=/dashboard
  3. 用户呼叫/login?key=112233
  4. 登录页面订阅AuthService并创建用户令牌和重定向/dashboard
  5. 在渲染/dashboard触发之前 AuthGuard 和 AuthGurad 让他们一切都很好
  6. /dashboard正常渲染
  7. 用户想要导航/claim/search page
  8. 路由器更改页面 URL 但router-outlet不呈现重定向的组件
  9. 如果用户刷新窗口浏览器页面正常工作,否则SPA不工作

我在步骤 8,9 中的问题

我的路线:

const routes: Routes = [
  {
    path: '',
    redirectTo: 'dashboard',
    pathMatch: 'full',
  },
  {
    path: 'dashboard',
    component: DashboardPageComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'claim',
    canActivate: [AuthGuard],
    children: [{
      path: 'search',
      component: ClaimSearchPageComponent,
    },
    {
      path: 'detail/:id',
      component: ClaimDetailPageComponent,
    }]
  },
  {
    path: 'login',
    component: LoginPageComponent,
  },
  {
    path: 'error',
    component: ErrorPageComponent,
  },
  {
    path: '**',
    component: ErrorPageComponent,
  }
];

登录页面:

ngOnInit() {
    this._returnUrl = this._route.snapshot.queryParams['returnUrl'] || '/';
    this._encryptedKey = this._route.snapshot.queryParams['key'];
    this._authenticationService.login(this._encryptedKey)
      .subscribe(
        data => {
          this._router.navigate([this._returnUrl]);
        });
  }

认证服务:

public get isLogged(): boolean {
    return !!this.currentUserSubject.value;
}
public login(encryptedKey: string) {
    return super.httpPostModel(User, environment.apiService.endPoints.user.login, { key: encryptedKey }).pipe(map(user => {
        sessionStorage.setItem('currentUser', JSON.stringify(user));
        this.currentUserSubject.next(user);
        return user;
    }));
}

认证卫士

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this._authenticationService.isLogged) {
        return true;
    }
    this._router.navigate(['/error'], { queryParams: { returnUrl: state.url } });
    return false;
}
4

2 回答 2

1

对于无组件路由(没有路由器出口),您可以使用 canActivateChild而不是canActivate,我建议您添加仅包含该内容的 ClaimComponent

<router-outlet></router-outlet>

并将路线更改为

{
 path: 'claim',
 component: ClaimComponent, // add this
 canActivate: [AuthGuard],
 children: [{
   path: 'search',
   component: ClaimSearchPageComponent,
 },
 {
   path: 'detail/:id',
   component: ClaimDetailPageComponent,
 }]
},

在无组件路由的情况下, canActivateChild 在任何子路由被激活之前运行:

{
 path: 'claim',
 canActivateChild: [AuthGuard],
 children: [{
   path: 'search',
   component: ClaimSearchPageComponent,
 },
 {
   path: 'detail/:id',
   component: ClaimDetailPageComponent,
 }]
},
于 2019-11-29T09:06:44.670 回答
0

在您的路线中,您还需要为父组件(声明组件)指定组件属性。

尝试这个 :

{
    path: 'claim',
    component: ClaimPAgeComponent,
    canActivate: [AuthGuard],
    children: [{
      path: 'search',
      component: ClaimSearchPageComponent,
    },
    {
      path: 'detail/:id',
      component: ClaimDetailPageComponent,
    }]
  }
于 2019-11-29T09:05:28.237 回答