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私人局辅助,WPK透视挂件工具(往昔真的是有辅助器)AI 智能体黑科技再上新...
我来分享!we-poker辅助... 我来分享!we-poker辅助软件教程,德扑之星辅助软件神器(素来有透视)主打本地运行的 AI 黑科...
必胜教程!wepoker辅助软... 必胜教程!wepoker辅助软件价格,微扑克外卦神器软件助手(一直是有透视)AI 是一款可以让一直输...
今日公布!wepoker私人局... 您好,今日公布!wepoker私人局辅助挂,德普之星哪里有挂平台(一直存在有开挂)这款游戏可以开挂的...
一分钟教会你!wepoker怎... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
可靠教程!we poker游戏... 您好:we poker游戏下这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用...
发现一款!!德扑圈透视,WPK... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成德扑圈透视解析、 AI 处理、德扑圈...
关于!德普之星私人局透视,we... 关于!德普之星私人局透视,wepoker透视是真的吗软件(切实真的有透视)主打本地运行的 AI 黑科...
必赢方法!wepoker破解版... 必赢方法!wepoker破解版内购,wepoker是如何开挂的教程(原来真的是有透视挂)AI 智能体...
重大发现!wepoker免费辅... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wepoker免费辅助器解析、 AI...