【问题标题】:How to write condition in route in angular / ionic如何在角度/离子的路线中写入条件
【发布时间】:2021-01-04 08:31:45
【问题描述】:

我正在使用 ionic 5 框架来构建应用程序,如果用户在更改路由之前已经登录,我想在路由中添加条件。

app-routing.module.ts 文件:

const routes: Routes = [
    {
        path: '',
        redirectTo: 'home',
        pathMatch: 'full'
    },
    {
        path: 'home',
        loadChildren: './home/home.module#HomePageModule'
    },
    {
        path: 'doctors',
        loadChildren: () => import('./doctors/doctors.module').then(m => m.DoctorsPageModule)
    },
    {
        path: 'dashboard',
        loadChildren: () => import('./user/dashboard/dashboard.module').then(m => m.DashboardPageModule),
        canLoad: [AuthGuard],
    },
];

@NgModule({
    imports: [
        RouterModule.forRoot(routes, {preloadingStrategy: PreloadAllModules})
    ],
    exports: [RouterModule]
})
export class AppRoutingModule {
}

我想在此处添加条件

       {
            path: '',
            redirectTo: 'home',
            pathMatch: 'full'
        },

如果用户已经签名,将 redirectTo: 'home' 更改为 redirectTo: 'dashboard' 我该怎么做?

注意:我使用AuthGuard 来阻止用户登录某些 溃败

【问题讨论】:

  • 您是否管理任何本地存储以检查用户是否已登录?
  • @RohitTagadiya 是的,我做到了。我用AuthGuard 来检查它。
  • 然后登录后如果你得到令牌,那么你可以将它存储在本地存储中,当你进入home页面时,检查令牌是否存储在本地存储然后重定向到dashboard否则,需要登录...

标签: angular router ionic5


【解决方案1】:

你必须使用你的 AuthGuard,但是 canActivate 功能,像这样:

路线:

 {
     path: 'dashboard',
     loadChildren: () => import('./user/dashboard/dashboard.module').then(m => m.DashboardPageModule),
     canLoad: [AuthGuard],
     canActivate: [AuthGuard]
 },

AuthGuard

constructor(private router:Router) {}

canLoad = () => {//...your code }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
   if (!isLoggedIn()) { //your verification to logged In
       
      this.router.navigate(['/']);
      return false;
    }
    return true;   
}

最后,在您的 HomeComponent 中,如果已登录,您会重定向。

HomeComponent.ts

ngOnInit(): void {
   if(isLoggedIn()) this.router.navigate(['dashboard']);
}

【讨论】:

  • canActivatecanLoad 有什么区别
  • canActivate 用于防止未经授权的用户访问某些路由。 canLoad 用于防止应用程序在未授权用户的情况下延迟加载整个模块。
【解决方案2】:
/***** gaurd */

@Injectable()
export class checkLogged {
  canActivate() {
    //check user is logged in
  }
}

const routes: Routes = [
    {
        path: '',
        redirectTo: 'dashboard',
        pathMatch: 'full', 
        canActivate: [checkLogged]
    },
    {
        path: '',
        redirectTo: 'home',
        pathMatch: 'full'
    },
    {
        path: 'home',
        loadChildren: './home/home.module#HomePageModule'
    },
    {
        path: 'doctors',
        loadChildren: () => import('./doctors/doctors.module').then(m => m.DoctorsPageModule)
    },
    {
        path: 'dashboard',
        loadChildren: () => import('./user/dashboard/dashboard.module').then(m => m.DashboardPageModule),
        canLoad: [AuthGuard],
    },
];

@NgModule({
    imports: [
        RouterModule.forRoot(routes, {preloadingStrategy: PreloadAllModules})
    ],
    exports: [RouterModule]
})
export class AppRoutingModule {
}

【讨论】:

    【解决方案3】:

    auth 守卫是一个角度路由守卫,用于防止未经身份验证或未经授权的用户访问受限制的路由,它通过实现 CanActivate 接口来实现这一点,该接口允许守卫决定路由是否可以使用 canActivate() 方法激活。如果方法返回 true 则路由被激活(允许继续),否则如果方法返回 false 则路由被阻塞。

    auth guard 使用身份验证服务来检查用户是否登录,如果他们登录,它会检查他们的角色是否被授权访问请求的路由。如果他们已登录并获得授权,则 canActivate() 方法返回 true,否则返回 false 并将用户重定向到登录页面。

    Angular 路由保护附加到路由器配置中的路由,此身份验证保护用于 app.routing.ts 以保护主页和管理页面路由。

    import { Injectable } from '@angular/core';
    import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    
    import { AuthenticationService } from '@app/_services';
    
    @Injectable({ providedIn: 'root' })
    export class AuthGuard implements CanActivate {
        constructor(
            private router: Router,
            private authenticationService: AuthenticationService
        ) { }
    
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
            const currentUser = this.authenticationService.currentUserValue;
            if (currentUser) {
                // check if route is restricted by role
                if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
                    // role not authorised so redirect to home page
                    this.router.navigate(['/']);
                    return false;
                }
    
                // authorised so return true
                return true;
            }
    
            // not logged in so redirect to login page with the return url
            this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
            return false;
        }
    }

    【讨论】:

      【解决方案4】:

      你可以使用解析器来解决这个问题,比如TestResolverService:

      import { Injectable } from '@angular/core';
      import { Resolve, ActivatedRouteSnapshot, Router } from '@angular/router';
      import { AuthService } from '@core/services/auth/auth.service';
      import { Observable } from 'rxjs';
      import { map } from 'rxjs/operators';
      
      @Injectable({
        providedIn: 'root',
      })
      export class TestResolverService implements Resolve<any> {
        constructor(private router: Router, public authService: AuthService) {}
      
        resolve(route: ActivatedRouteSnapshot): Observable<any> | Promise<any> | any {
      // or anyhow you specify if user is signed in or not 
          return this.authService.subjectUser.pipe(
            map((user) => {
              const isAuth = !!user;
              if (isAuth) {
                this.router.navigate(['/dashboard']);
              } else {
                this.router.navigate(['/home']);
                return false;
              }
            })
          );
        }
      }
      

      在你的 routerModule 中:

      { path: '', resolve: { TestResolverService }, children: [] },
      {
          path: 'home',
          loadChildren: './home/home.module#HomePageModule'
      },
      {
          path: 'doctors',
          loadChildren: () => import('./doctors/doctors.module').then(m => m.DoctorsPageModule)
      },
      {
          path: 'dashboard',
          loadChildren: () => import('./user/dashboard/dashboard.module').then(m => m.DashboardPageModule),
          canLoad: [AuthGuard],
      },
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-14
        • 1970-01-01
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 2018-08-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多