Angular路由:嵌套路由正确重定向到404页面的方法
创始人
2024-10-28 06:01:13
0

在Angular中想要正确地将嵌套路由重定向到404页面,可以使用路由守卫。

首先,在app.module.ts中引入守卫和自定义的404组件。

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { AuthGuard } from './auth.guard';

const appRoutes: Routes = [
  {
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full'
  },
  {
    path: 'dashboard',
    canActivate: [AuthGuard],
    loadChildren: './dashboard/dashboard.module#DashboardModule'
  },
  {
    path: '**',
    component: PageNotFoundComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

接下来,创建一个AuthGuard守卫,在这个守卫里面从路由树中查找一个路由是否存在,如果存在,就继续导航,否则就导航到404页面。

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

@Injectable()
export class AuthGuard implements CanActivate {
  
  constructor(private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable | Promise | boolean {

    const url: string = state.url;
    
    return this.checkRoute(next, url);
  }

  checkRoute(route: ActivatedRouteSnapshot, url: string): boolean {
    if (route.routeConfig && route.routeConfig.path) {
      return true;
    } else {
      this.router.navigate(['/404']);
      return false;
    }
  }
}

最后,创建一个404组件,用于显示404页面。

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-page-not-found',
  templateUrl: './page-not-found.component.html',
  styleUrls: ['./page-not-found.component.scss']
})
export class PageNotFoundComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

这样就可以正确地将嵌套路由重定向到404页面了。

相关内容

热门资讯

实测揭晓!wepoker怎么设... 实测揭晓!wepoker怎么设置房间(辅助挂)本来有挂(有挂规律)1、点击下载安装,wepoker怎...
盘点一款!wepoker透视器... 盘点一款!wepoker透视器免费(辅助挂)其实真的有挂(有挂秘笈)亲,关键说明,wepoker透视...
重大通报!德州局hhpoker... 重大通报!德州局hhpoker(辅助挂)确实有挂(有挂方式)1、许多玩家不知道德州局hhpoker辅...
带你了解!sohoo辅助(辅助... 带你了解!sohoo辅助(辅助挂)一直有挂(有挂神器)1)sohoo辅助辅助插件:进一步探索soho...
终于懂了!如何判断wpk辅助软... 终于懂了!如何判断wpk辅助软件的真假(辅助挂)果然真的是有挂(竟然有挂)1、如何判断wpk辅助软件...
必备教程!hhpoker买挂(... 必备教程!hhpoker买挂(辅助挂)真是有挂(有挂分享)在进入hhpoker买挂软件靠谱后,参与本...
推荐一款!wepoker辅助器... 推荐一款!wepoker辅助器有哪些功能(辅助挂)真是真的是有挂(有挂功能)1、wepoker辅助器...
玩家必用!wepoker辅助分... 玩家必用!wepoker辅助分析器(辅助挂)本来有挂(今日头条)1、起透看视 wepoker辅助分析...
必看攻略!wepoker提高好... 必看攻略!wepoker提高好牌率(辅助挂)竟然存在有挂(有挂分享)1、玩家可以在wepoker提高...
专业讨论!哈糖大菠萝攻略(辅助... 专业讨论!哈糖大菠萝攻略(辅助挂)果然存在有挂(讲解有挂)1、超多福利:超高返利,海量正版游戏,哈糖...