我有一个路由模块routing.module.ts文件,我想在其中更改redirectTo路径,这取决于用户是否是管理员。
我的想法是使用服务来捕获和保留价值,这将有助于维持价值,但价值不会改变。我尝试了许多方法,但无法正常工作。有什么想法吗?
在routing.module.ts上有我当前的代码
将提供任何帮助,以帮助其工作并解释该过程
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { TabsPage } from './tabs.page';
import { DataService } from '../services/data.service'
const routes: Routes = [
{
path: '',
component: TabsPage,
children: [
{
path: '',
redirectTo: DataService.prototype.isAdmin() ? 'home' : 'dashboard',
pathMatch: 'full'
},
{
path: 'home',
children: [
{
path: '',
loadChildren: () =>
import('../home/home.module').then(m => m.HomePageModule)
}
]
},
{
path: 'dashboard',
children: [
{
path: '',
loadChildren: () =>
import('../dashboard/dashboard.module').then(m => m.DashboardPageModule)
}
]
},
{
path: 'profile',
children: [
{
path: '',
loadChildren: () =>
import('../profile/profile.module').then(m => m.ProfilePageModule)
}
]
},
{
path: 'menu',
children: [
{
path: '',
loadChildren: () =>
import('../menu/menu.module').then(m => m.MenuPageModule)
}
]
},
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class TabsPageRoutingModule {}
和data.service.ts文件
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable({
providedIn: 'root'
})
export class DataService {
User = {
isAdmin: false
}
constructor(
private storage: Storage,
) { }
setUser(isAdmin: boolean) {
this.User.isAdmin = isAdmin
}
isAdmin() {
return this.User.isAdmin
}
}
使用gaurd不要在路由模块中进行更改,它将解决您的问题
示例
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from '../auth.service';
import { ToastrService } from 'ngx-toastr';
@Injectable({
providedIn: 'root'
})
export class SetupToolsGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router,private toaster:ToastrService) {}
canActivate(): boolean {
const token = this.authService.decodeToken();
// parent and sub user access
if (token && (token.user_type_id === 0 || token.user_type_id === 2 || token.user_type_id === 3 || token.user_type_id === 4)) {
console.log('norId',this.authService.getNorId())
if(this.authService.getNorId()!=null){
return true;
}
else{
if(token.user_type_id===2){
this.router.navigate(['Admin/admin-dashboard'])
}
if(token.user_type_id===0){
this.router.navigate(['dashboard'])
}
if(token.user_type_id===1){
this.router.navigate(['/superadmin/superadmin-dashboard'])
}
if(token.user_type_id===3){
this.router.navigate(['/tech/tech-support'])
}
this.toaster.error('Access Denied! Please follow the steps to create nor file', '', {
timeOut: 3000
});
return false;
}
}
else {
if(token)
{
this.router.navigate(['access-denied'])
return false;
}
else{
this.router.navigate([''])
return false;
}
}
}
}
添加路线gaurd是处理的最佳方法
路由模块
app.routing.module中的示例路径
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard,UserGuard],
}