CreepPlays
CreepPlays

Reputation: 23

Angular 2 New router - detect 404

Is it possible to detect with the new router of Angular2 if the current route exists or if it ends into a 404 error? So I can set it back to the default route "/".

I found nothing, I searched for an hour but found only things for the deprecated router.

Upvotes: 2

Views: 1729

Answers (3)

Morteza Manavi
Morteza Manavi

Reputation: 33216

You can add this route at the end of your Routes which means Angular 2 RC1 router will go to this MyDefaultComponent if none of the other defined routes matches the requested URL:

{ path: '**', component: MyDefaultComponent }

Upvotes: 4

Ajain Vivek
Ajain Vivek

Reputation: 1121

I had the same issue. The only way to do in angular 2 as per latest doc is

  1. Redirect to pagenotfound when route doesn't match with any pattern

{ path: '**', redirectTo: 'pagenotfound' }

  1. Navigate to component without URL change

{ path: '**', component: SomeComponent }

Upvotes: 1

Danziger
Danziger

Reputation: 21181

You can use a wildcard to do that and either redirect to any other route or have a 404 component for that:

@RouteConfig([
    { path: '/', name: 'Welcome', component: WelcomeComponent, useAsDefault: true },
    { path: '/products', name: 'Products', component: ProductListComponent },
    { path: '/product/:id', name: 'ProductDetail',  component: ProductDetailComponent },

    // Redirect option:
    // { path: '/**', redirectTo:['Welcome'] },

    // Not found component option:
    // {path: '/**', component: NotFoundComponent},

    // Both together:
    { path: '/not-found', name: 'NotFound', component: NotFoundComponent},
    { path: '/**', redirectTo:['NotFound'] },
])

Note that in the version of Angular that I'm using right now, 2.0.0-beta.15, if you put just path: '/*' it won't work, see here.

Upvotes: 1

Related Questions