如何确定具有路径值的路由

How to Determine a Route With Path Value

拜托,我在解决这种情况时遇到了一些挑战。 每当我的应用程序启动时,它都会转到没有 url 路径值 (http://localhost:4200/) 的 DummyComponent。这只有两个按钮,登录和注册。等待您点击的任何按钮;它导航到页面。

假设用户单击登录按钮以授权进入系统,一旦成功,用户将被重定向到仪表板组件 => http://localhost:4200/dashboard.

现在,即使用户已登录并手动将 url 更改为 http://localhost:/4200。这没有路径值,如何将用户重定向回 http://localhost:4200/dashboard

我知道我可以使用 canActivate 守卫来保护我的路线,但我面临的挑战是;如何确定用户何时访问没有路径值的 url,即 http://localhost:4200/(登录时),以便我可以将用户重定向回仪表板? ……但是同样,当用户没有登录并且没有路径访问url时,它应该直接进入初始的DummyComponent。

我的路线是这样的

const routes4: Routes = [
   {path: '', component: DummyComponent},
   {
     path: '',
     runGuardsAndResolvers: 'always',
     canActivate: [AuthGuard],
     children: [
      { path: 'dashboard', component: DashboardComponent },
       { path: 'user/list', component: PatientsComponent },
       { path: 'user/new', component: PatientComponent },
       { path: '**', redirectTo: 'dashboard', pathMatch: 'full'}
     ]
   },
];
****
canActivate(): boolean {
      if (this.authService.isLoggedIn()) {
        return true;
      }
      this.pnotifyService.error('Error', 'You do not have sufficient permission');
      this.router.navigate(['/login']);
      return false;
  }

我做了一些研究,但无法掌握像我这样的场景。任何关于如何解决这个问题的想法都将受到高度赞赏。 非常感谢。

您可以根据您的情况使用另一个 gaurd 将用户重定向到正确的路径

像这样:

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

@Injectable()
export class RedirectGuard implements CanActivate {
  canActivate() {

    if (this.authService.isLoggedIn()) {
         // when user is logged in you redirect it to dashboard url
         this.router.navigate(['dashboard']);
         return true;
    }
  }
 //Constructor 
 constructor(private router: Router, private authService: AuthService) { }
}

现在您可以像这样在您的路径中使用它:

const routes4: Routes = [
   {path: '', component: DummyComponent},
   {
     path: '',
     runGuardsAndResolvers: 'always',
     canActivate: [AuthGuard, RedirectGuard],
     children: [
      { path: 'dashboard', component: DashboardComponent },
       { path: 'user/list', component: PatientsComponent },
       { path: 'user/new', component: PatientComponent },
       { path: '**', redirectTo: 'dashboard', pathMatch: 'full'}
     ]
   },
];

更新:

您可以重新使用现有代码来实现此行为

像这样:

canActivate(): boolean {
      if (this.authService.isLoggedIn()) {
        this.router.navigate['/dashboard'] //redirect if the user is logged in
        return true;
      }
      this.pnotifyService.error('Error', 'You do not have sufficient permission');
      this.router.navigate(['/login']);
      return false;
  }