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

相关内容

热门资讯

透视规律!wpk辅助软件(透视... 透视规律!wpk辅助软件(透视)丽水都莱app辅助(其实是真的辅助插件)-哔哩哔哩在进入丽水都莱ap...
透视软件!wepoker辅助器... 透视软件!wepoker辅助器安装包定制(透视)九九山城万州版脚本(切实有辅助软件)-哔哩哔哩1、九...
为了进一步!模拟器打开hhpo... 为了进一步!模拟器打开hhpoker(透视)丽水都莱app辅助(确实真的是有辅助软件)-哔哩哔哩所有...
一直以来!wepoker安装教... 一直以来!wepoker安装教程(透视)wepoker辅助软件(总是存在有辅助辅助器)-哔哩哔哩1、...
出现新变化!wpk辅助是什么(... 出现新变化!wpk辅助是什么(透视)友友联盟辅助软件下载(真是真的是有辅助app)-哔哩哔哩友友联盟...
近年来!哈糖大菠萝攻略(透视)... 近年来!哈糖大菠萝攻略(透视)新众亿免费辅助(总是是有辅助插件)-哔哩哔哩一、新众亿免费辅助可以开透...
透视智能ai!hhpoker德... 透视智能ai!hhpoker德州机器人(透视)老友麻将开挂辅助器(真是有辅助软件)-哔哩哔哩;1、老...
有玩家发现!wepoker有没... 有玩家发现!wepoker有没有挂(透视)陕麻圈插件开挂(竟然存在有辅助下载)-哔哩哔哩1、操作简单...
透视线上!wepoker辅助是... 透视线上!wepoker辅助是真的吗(透视)禅游指尖四川作必弊(都是是真的辅助软件)-哔哩哔哩1、下...
透视中牌率!aa poker辅... 透视中牌率!aa poker辅助(透视)广西友乐解码器(总是存在有辅助神器)-哔哩哔哩1、任何广西友...