check if a route exist in angular 2

*爱你&永不变心* 提交于 2019-12-10 22:16:38

问题


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?


回答1:


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]);

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:


You can use {path: '**', redirectTo: ['home']} add this route at the end of the all routes.




回答3:


As stated here by user @Théophile Godard
You can make usage of

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');
  });

This doesn't redirect and you can handle the try to route to non existing route.




回答4:


The answer from @Sajeetharan concerning router.config is correct but is somewhat over simplified and does not work for routes with URL params in them like '/books/:id' or child routes.

Also lets throw this into a service for reuse:

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
  }
}

Then just call it from elsewhere:

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

Or to check the current route simply:

const isRouteValid = this.routerHelperService.isRouteValid()

Of course, we need to inject RouterHelperService into the constructor where it is used.

constructor(private routerHelperService: RouterHelperService) {}


来源:https://stackoverflow.com/questions/50850125/check-if-a-route-exist-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!