Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect non-matching routes in Angular 2 [duplicate]

I am looking for equivalent of $urlRouterProvider.otherwise in Angular 2.

More details:

I have a router definition like this:

@RouteConfig([
  { path: "/", component: MultiPost, name: "Home", useAsDefault: true },
  { path: "/m/:collectionName/:categoryName/:page", component: MultiPost, name: "MultiPost" }
])

Both routes are working perfectly, for instance when I hit / or /m/sth/sth/0 I got what I want.

But when I hit a random url like /kdfsgdshdjf nothing happens. Page is rendered and <router-outlet> is empty since no route is matched.

What I want to do is to redirect all non matching routes to a default one. I need something like $urlRouterProvider.otherwise("/");.

Does anyone knows how to do that?

like image 829
Umut Benzer Avatar asked Jan 20 '16 17:01

Umut Benzer


2 Answers

There is no 'otherwise' route in angular 2 yet. But the same functionality can be achieved using wildcard parameter, like so:

@RouteConfig([
    { path: '/', redirectTo: ['Home'] },
    { path: '/home', name: 'Home', component: HomeComponent },
    // all other routes and finally at the last add
    {path: '/*path', component: NotFound}

This will only load the 'NotFound' component and the url will be same as what you navigate to. In case you want all not matching routes to redirect to a '404' url, you can do something like:

//at the end of the route definitions
{ path: '/404', name: '404', component: PageNotFoundComponent },
{ path: '/*path', redirectTo:['404'] }
like image 70
Saurabh Maurya Avatar answered Nov 11 '22 17:11

Saurabh Maurya


This feature hasn't been implemented yet:

https://github.com/angular/angular/issues/2965

like image 33
Langley Avatar answered Nov 11 '22 15:11

Langley