4

我想检查角度项目中是否存在路线。例如,用户http://localhost:4200/#/timestamp在 url 栏中输入并且timestamp在项目中不存在,您将如何在不重定向的情况下进行检查?

4

5 回答 5

6

配置中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);
}
于 2018-06-14T05:26:43.177 回答
5

@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) {}
于 2019-04-01T12:20:41.437 回答
1

正如用户@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');
  });

这不会重定向,您可以处理尝试路由到不存在的路由。

于 2018-12-10T19:56:31.117 回答
1

您可以{path: '**', redirectTo: ['home']}在所有路线的末尾使用添加此路线。

于 2018-06-14T05:31:32.483 回答
0

我知道我参加聚会迟到了,但我仍然想这样做。对这里的答案不满意,我决定采用最简单的解决方案。在我的模块中,我以标准方式定义路由模块:

@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。

于 2021-04-19T17:16:01.490 回答