Angular 如何在角/离子型布线中写入条件

Angular 如何在角/离子型布线中写入条件,angular,router,ionic5,Angular,Router,Ionic5,我正在使用ionic 5框架构建一个应用程序,如果用户在更改路由之前已经登录,我想在路由中添加条件 应用程序路由.module.ts文件: const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', loadChildren: './home/home.module#

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

应用程序路由.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'
        },
如果用户已签名,请将更改
重定向到:'home'
更改为
重定向到:'dashboard'
如何执行此操作

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


您必须使用AuthGuard,但可以激活功能,如下所示:

路线:

 {
     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中,如果loggedIn

HomeComponent.ts

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

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

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

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

角度路由防护装置连接到路由器配置中的路由,此身份验证防护装置用于app.routing.ts保护主页和管理页路由

从'@angular/core'导入{Injectable};
从'@angular/Router'导入{Router,CanActivate,ActivatedRouteSnapshot,RouterStateSnashot};
从'@app/_services'导入{AuthenticationService};
@可注射({providedIn:'root'})
导出类AuthGuard实现了CanActivate{
建造师(
专用路由器:路由器,
私有authenticationService:authenticationService
) { }
canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot){
const currentUser=this.authenticationService.currentUserValue;
如果(当前用户){
//检查路由是否受角色限制
if(route.data.roles&&route.data.roles.indexOf(currentUser.role)=-1){
//角色未授权,因此重定向到主页
this.router.navigate(['/']);
返回false;
}
//因此,请返回true
返回true;
}
//未登录,所以重定向到带有返回url的登录页面
this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}});
返回false;
}

}
您是否管理本地存储以检查用户是否已登录?@RohitTagadiya是的,我管理过。我使用了
AuthGuard
来检查它。然后在登录后,如果您正在获取令牌,那么您可以将其存储在本地存储中。当您进入
主页
页面时,检查令牌是否存储在本地存储中,然后重定向到
仪表板
,否则,需要登录…使用
canActivate
canLoad
canActivate之间的区别来防止未经授权的用户访问某些路由。canLoad用于防止应用程序在未经授权的情况下延迟加载整个模块。
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],
},