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

相关内容

热门资讯

透明攻略!传奇扑克辅助(辅助挂... 透明攻略!传奇扑克辅助(辅助挂)果真真的有挂(详细教程)(有挂规律)-哔哩哔哩关于传奇扑克辅助的基本...
透视辅助(来玩德州app有挂)... 透视辅助(来玩德州app有挂)辅助透视(辅助挂)的确真的有挂(有挂总结)-哔哩哔哩;来玩德州app有...
一分钟了解!德扑ai操作(透视... 大家肯定在之前德扑ai操作或者德扑ai操作中玩过一分钟了解!德扑ai操作(透视)确实真的有挂(详细教...
我来教教大家!哈糖大菠萝拿好牌... 我来教教大家!哈糖大菠萝拿好牌,欢乐棋牌有挂,确实是真的有挂(有挂教学)-哔哩哔哩1、让任何用户在无...
透视代打(fishpoker下... 透视代打(fishpoker下载)软件透明挂(辅助挂)原来是真的有挂(有挂攻略)-哔哩哔哩准备好在f...
重大通报!德州ai辅助app(... 重大通报!德州ai辅助app(辅助挂)其实真的有挂(详细教程)(有挂总结)-哔哩哔哩1、点击下载安装...
重大通报!德州nzt实战,云扑... 重大通报!德州nzt实战,云扑克确实真的有挂,确实真的有挂(有挂技巧)-哔哩哔哩;亲真的是有正版授权...
透视系统!poker辅助工具(... 1、透视系统!poker辅助工具(辅助挂)确实是真的有挂(详细教程)(有挂详情)-哔哩哔哩(UU p...
分享开挂内幕!德州wpk辅助真... 分享开挂内幕!德州wpk辅助真的(透视)其实真的有挂(详细教程)(有挂总结)-哔哩哔哩关于德州wpk...
玩家必用(德州辅助)辅助透视(... 玩家必用(德州辅助)辅助透视(辅助挂)原来是真的有挂(有挂了解)-哔哩哔哩;1分钟了解详细教程(微信...