我想检查角度项目中是否存在路线。例如,用户http://localhost:4200/#/timestamp
在 url 栏中输入并且timestamp
在项目中不存在,您将如何在不重定向的情况下进行检查?
5 回答
配置中no way to check
是否存在路由路径,但是您可以使用**
路由器配置模块在配置中进行重定向。
export const AppRoutes = [
{ path: "", redirectTo: "home", pathMatch: "full" },
{ path: '**', redirectTo: 'home'}
];
或者在您的组件中执行此操作,
string redirectUrl = "http://localhost:4200/#/timestamp";
this.redirectUrl = this.redirectUrl ? this.redirectUrl : '/home';
this.router.navigate([this.redirectUrl]);
或者如果你想遍历所有配置的路由,你可以从 router.config 获取路由
for (var i = 0; i < this.router.config.length; i++) {
var routePath:string = this.router.config[i].path;
console.log(routePath);
}
@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 lets 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注入到使用它的构造函数中。
constructor(private routerHelperService: RouterHelperService) {}
正如用户@Théophile Godard所说,您可以使用
this.router.navigate(['redirect'])
.then(data => {
console.log('Route exists, redirection is done');
})
.catch(e => {
console.log('Route not found, redirection stopped with no error raised');
});
这不会重定向,您可以处理尝试路由到不存在的路由。
您可以{path: '**', redirectTo: ['home']}
在所有路线的末尾使用添加此路线。
我知道我参加聚会迟到了,但我仍然想这样做。对这里的答案不满意,我决定采用最简单的解决方案。在我的模块中,我以标准方式定义路由模块:
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class MyRoutingModule {}
并将路由定义为常量。我从这个模块导出了一个函数:
export function isMyRouteAvailable(childPath: string): boolean {
if (routes.length > 0 && routes[0].children) {
for (let i = 0; i < routes[0].children.length; i++) {
if (routes[0].children[i].path === childPath) {
return true;
}
}
}
return false;
}
不使用任何角度魔法或任何东西。只需遍历我必须定义的结构,以便首先将路由创建到我的模块中。
因此,现在当我们构建后端时,可以检查从服务返回的选项,以查看我们是否在向用户提供按钮之前实现了 UI。