首页 > 解决方案 > Angular - 应用程序在手动页面刷新时未正确路由

问题描述

在我的 Angular 应用程序中,我设置了app.routing.ts如下所示的路由:

const routes: Routes = [{
    path: '',
    redirectTo: '/login',
    pathMatch: 'full',
    canActivate: [LoginGuard]
},
{
    path: 'login',
    component: LoginComponent,
    canActivate: [LoginGuard]
},
{
    path: '',
    component: AdminLayoutComponent,
    canActivate: [AuthGuardService],
    data: {
        expectedRole: 'Admin'
    },
    children: [{
        path: '',
        loadChildren: './layouts/admin-layout/admin-layout.module#AdminLayoutModule'
    }]
},
{
    path: 'customer_dashboard',
    component: CustomerLayoutComponent,
    canActivate: [AuthGuardService],
    data: {
        expectedRole: 'Customer'
    },
    children: [{
        path: '',
        loadChildren: './layouts/customer-layout/customer-layout.module#CustomerLayoutModule'
    }]
},
{
    path: '',
    component: MobiLayoutComponent,
    canActivate: [AuthGuardService],
    data: {
        expectedRole: 'Mobilink'
    },
    children: [{
        path: '',
        loadChildren: './layouts/mobi-layout/mobi-layout.module#MobiLayoutModule'

    }]
},

{
    path: '**',
    redirectTo: 'login',
    pathMatch: 'full'
}
];

@NgModule({
imports: [
    CommonModule,
    BrowserModule,
    NgxUiLoaderModule.forRoot(ngxUiLoaderConfig),
    RouterModule.forRoot(routes),
],
exports: [],
})
export class AppRoutingModule {}

这是我的登录验证守卫

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { LoginAuthenticateService } from './login-authenticate.service';
import * as decode from 'jwt-decode';

@Injectable()
export class LoginAuthenticateGuardService implements CanActivate {

constructor(public auth:LoginAuthenticateService,public router:Router) {
}

canActivate():boolean{
if (this.auth.isAuthenticated()) {
  const token = localStorage.getItem('token');
  const tokenPayload = decode(token);
  const user_role=tokenPayload['role'].toString();
  if(user_role=='Admin')
  {
   this.router.navigate(['dashboard']);
   return false;
  }
  else if(user_role=='Customer')
  {
    this.router.navigate(['customer_dashboard']);
    return false;
  }
  else if(user_role=='Mobilink')
  {
    this.router.navigate(['mobilink_dashboard']);
    return false;
  }
}
return true;

}

}

除了一个奇怪的问题外,一切都运行localhost:4200良好页面 localhost:4200/login/login 我什么也没得到。localhost:4200/loginlocalhot:4200/login/login

标签: angularangular4-router

解决方案


推荐阅读