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页面了。

相关内容

热门资讯

2026版辅助挂!牵手游戏ap... 2026版辅助挂!牵手游戏app辅助器,心悦踢辅助软件-其实真的是有辅助神器(哔哩哔哩)1、完成牵手...
反观!金州水鱼脚本,永盛联盟辅... 反观!金州水鱼脚本,永盛联盟辅助脚本-其实真的是有辅助插件(哔哩哔哩)1、下载好永盛联盟辅助脚本脚本...
方法辅助挂!新漫游免费辅助器,... 方法辅助挂!新漫游免费辅助器,新海贝之城脚本-竟然存在有辅助脚本(哔哩哔哩)在进入新漫游免费辅助器软...
代打辅助挂!微信老铁13水辅助... 代打辅助挂!微信老铁13水辅助,仙神互娱辅助-果然确实有辅助器(哔哩哔哩)1、任何微信老铁13水辅助...
黑科技辅助挂!乐酷副厅外卖辅助... 黑科技辅助挂!乐酷副厅外卖辅助,掌中乐游戏辅助工具-好像真的是有辅助工具(哔哩哔哩)1、下载好掌中乐...
今日!桃乐甘肃麻将辅助器,天天... 今日!桃乐甘肃麻将辅助器,天天福建十三兵修改器-一贯存在有辅助挂(哔哩哔哩)1、任何天天福建十三兵修...
透视免费!新九天作必弊系统,赣... 透视免费!新九天作必弊系统,赣湘互娱辅助-切实是真的有辅助神器(哔哩哔哩)1、玩家可以在新九天作必弊...
截至目前!金虎爷辅助器,新51... 截至目前!金虎爷辅助器,新518互游插件下载-真是是真的有辅助神器(哔哩哔哩)1、下载好新518互游...
截至发稿!蜀山四川辅助脚本,福... 截至发稿!蜀山四川辅助脚本,福建天天开心辅助工具下载-真是真的是有辅助app(哔哩哔哩)1、上手简单...
随着!杭州都莱大菠萝买了挂有用... 随着!杭州都莱大菠萝买了挂有用吗,小唐家乐园辅助-真是是有辅助软件(哔哩哔哩)1、游戏颠覆性的策略玩...