gpt4 book ai didi

angular - 检查 Angular 2 中是否存在路线

转载 作者:行者123 更新时间:2023-12-03 00:16:24 24 4
gpt4 key购买 nike

我想检查 Angular 项目中是否存在路线。例如,用户在地址栏中输入http://localhost:4200/#/timestamp,而项目中不存在timestamp,那么如何在不存在的情况下进行检查重定向?

最佳答案

@Sajeetharan 关于 router.config 的答案是正确的,但有些过于简化,并且不适用于其中包含 URL 参数(如“/books/:id”或子路由)的路由.

此外,让我们将其放入服务中以供重用:

import { Injectable } from '@angular/core'
import { Router } from '@angular/router'

@Injectable({
providedIn: 'root'
})

export class RouterHelperService {

private validRouteRegices

constructor(private router: Router) {

const validRoutes = []

// router.config will not change so let's cache
// get all routes and child routes
this.router.config.forEach((route) => {
const routePath: string = route.path
validRoutes.push(routePath)
const routeChildren = route.children || []
routeChildren.forEach((routeChild) => {
const routeChildPath: string = route.path + '/' + routeChild.path
validRoutes.push(routeChildPath)
})
})

// swap routes for regices to support URL params and tidy up a little
this.validRouteRegices = validRoutes.map((route) => route.startsWith('/') ? route.replace('/', '') : route)
.map((route) => route.replace(/\/:[a-zA-Z]+/g, '/[a-zA-Z0-9]+'))
.filter((route) => route !== '' && route !== '**')
.map((route) => '^' + route + '$')
}

// call this to check if a route exists or not
isRouteValid(pathname = location.pathname): boolean {
let match = false
const locationPathname = pathname.startsWith('/') ? pathname.replace('/', '') : pathname
this.validRouteRegices.forEach((strValidRouteRegex: string) => {
const validRouteRegex = new RegExp(strValidRouteRegex)
if (validRouteRegex.test(locationPathname)) match = true
})
return match
}
}

然后从其他地方调用它:

const isRouteValid = this.routerHelperService.isRouteValid('/my/fave/path/with/id/800')

或者简单地检查当前路线:

const isRouteValid = this.routerHelperService.isRouteValid()

当然,我们需要将 RouterHelperService 注入(inject)到使用它的构造函数中。

constructor(private routerHelperService: RouterHelperService) {}

关于angular - 检查 Angular 2 中是否存在路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50850125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com