user8653311
user8653311

Reputation:

check if a route exist in angular 2

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?

Upvotes: 6

Views: 8995

Answers (5)

danday74
danday74

Reputation: 56936

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, let's 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 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
  }
}

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

Upvotes: 8

Tony the Tech
Tony the Tech

Reputation: 570

I know I'm late to the party, but I still wanted to do this. Not satisfied with the answers here, I decided on the simplest solution. In my module, I define the routing module in the standard way:

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class MyRoutingModule {}

and defined the routes as a const. I exported a function from this module:

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

Not using any angular magic or anything. Just traversing the structure which I had to define in order to create the routes into my module in the first place.

So now as we build out the back-end, options returned from the service can be checked to see if we have UI implemented before we offer a button to the user.

Upvotes: 0

Jo&#227;o Ghignatti
Jo&#227;o Ghignatti

Reputation: 2391

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.

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222522

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

Upvotes: 6

baj9032
baj9032

Reputation: 2582

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

Upvotes: 1

Related Questions