如何在 angular / ionic 的路由中写条件

How to write condition in route in angular / ionic

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

应用程序-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' 我该怎么做?

Note : I'm used AuthGuard to prevent user from signed into some routs

您必须使用您的 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']);
}
/***** 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 {
}

您可以使用解析器来解决这个问题,例如 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;
        }
      })
    );
  }
}

在你的路由器模块中:

{ 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],
},

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

auth guard 使用身份验证服务来检查用户是否登录,如果他们登录,它会检查他们的角色是否被授权访问所请求的路由。如果他们登录并授权 canActivate() 方法 returns true,否则 returns 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;
    }
}