本文介绍了检查角度 2 中是否存在路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查 angular 项目中是否存在路由.比如用户在url栏中输入http://localhost:4200/#/timestamp,项目中不存在timestamp,不知道怎么查重定向?

I want to check if a route exists in an angular project.For example user types http://localhost:4200/#/timestamp in the url bar and timestamp does not exist in the project, how will you be able to check without redirecting?

推荐答案

没有办法检查路由路径是否存在于配置中,但是你可以这样做在路由器配置模块中使用 ** 的配置重定向.

There is no way to check if the route path exists in the config, however you can do a redirect in configuration using ** in router config module.

export const AppRoutes = [
  { path: "", redirectTo: "home", pathMatch: "full" },
  { path: '**', redirectTo: 'home'}
];

或者在您的组件中执行此操作,

Or do this in your component,

string redirectUrl = "http://localhost:4200/#/timestamp";
this.redirectUrl = this.redirectUrl ? this.redirectUrl : '/home';
this.router.navigate([this.redirectUrl]);

或者如果你想遍历所有配置的路由,你可以从 router.config 获取路由

or if you want to loop over all the configured routes, you can get the routes from router.config

for (var i = 0; i < this.router.config.length; i++) {
        var routePath:string = this.router.config[i].path;
        console.log(routePath);
}

这篇关于检查角度 2 中是否存在路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 11:06