检查角度 2 中是否存在路线

4 angular-routing angular-ui-router angular angular-router auth-guard

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

dan*_*y74 7

@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
  }
}
Run Code Online (Sandbox Code Playgroud)

然后从其他地方调用它:

const isRouteValid = this.routerHelperService.isRouteValid('/my/fave/path/with/id/800')
Run Code Online (Sandbox Code Playgroud)

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

const isRouteValid = this.routerHelperService.isRouteValid()
Run Code Online (Sandbox Code Playgroud)

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

constructor(private routerHelperService: RouterHelperService) {}
Run Code Online (Sandbox Code Playgroud)


Saj*_*ran 6

还有no way to check,如果在配置中存在的路由路径,但是你可以做使用配置重定向**路由器配置模块。

export const AppRoutes = [
  { path: "", redirectTo: "home", pathMatch: "full" },
  { path: '**', redirectTo: 'home'}
];
Run Code Online (Sandbox Code Playgroud)

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

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

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

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