gpt4 book ai didi

Angular 6 基于 Angular 色的根 url 路由

转载 作者:行者123 更新时间:2023-12-05 07:26:20 25 4
gpt4 key购买 nike

我正在尝试为我的根 URL 实现基于 Angular 色的路由。例如,当用户登录时,我可以将他从 login.component 重定向到用户的仪表板页面。同样适用于管理员,也通过登录重定向到管理员仪表板页面。但是如果用户打开根 url,如何使用 Angular 色重定向到特定的仪表板?

目前我的根路由指向仪表板组件,该组件解析 Angular 色并重定向到所需的仪表板页面、用户或管理员。有没有办法消除仪表板组件?

AppRouting.ts

export const AppRoutes: Routes = [

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

{
path: '',
component: AdminLayoutComponent,
canActivate: [AuthGuard],
canLoad: [AuthGuard],
children: [
{
path: 'dashboard',
loadChildren: './dashboard/dashboard.module#DashboardModule'
},

DashboardRouting.ts

export const DashboardRoutes: Routes = [

{
path: '',
component: DashboardRedirectComponent,
},

测试 DashboardRedirect 组件:

export class DashboardRedirectComponent implements OnInit, AfterViewInit {

constructor(private auth: AuthenticationService, private router: Router) {

let currentUser = JSON.parse(localStorage.getItem('currentUser'));

if (this.auth.loggedIn()) {

if (currentUser['role'] == 'User') {
this.router.navigate(['/dashboard/user']);
}

if (currentUser['role'] == 'Admin') {
this.router.navigate(['/dashboard/admin']);
}
}
}

我尝试使用守卫甚至解析器来实现它,但没有成功。当我打开我的应用程序的根页面时,它导航到仪表板并在几秒钟后导航到相应的仪表板页面,但我想立即导航用户并且没有额外的组件。有什么建议吗?

最佳答案

您需要创建一个名为 RedirectGuard 的 Guard,如下所示:

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

@Injectable()
export class RedirectGuard implements CanActivate {
let currentUser = null;
let auth = null;

constructor(private authenticationService: AuthenticationService) {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.auth = authenticationService;
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
//Your redirection logic goes here

if (this.auth.loggedIn()) {

if (currentUser['role'] == 'User') {
this.router.navigate(['/dashboard/user']);
}

if (currentUser['role'] == 'Admin') {
this.router.navigate(['/dashboard/admin']);
}
}
return false;

}
}

AppRouting.ts 中使用 RedirectGuard 如下:

path: '',
component: AdminLayoutComponent,
canActivate: [RedirectGuard],
canLoad: [AuthGuard],
children: [
{
path: 'dashboard',
loadChildren: './dashboard/dashboard.module#DashboardModule'
},

关于Angular 6 基于 Angular 色的根 url 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54400484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com