2

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.

CreepPlays
  • 23
  • 4

3 Answers3

4

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 }
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Morteza Manavi
  • 33,026
  • 6
  • 100
  • 83
1

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.

Danziger
  • 19,628
  • 4
  • 53
  • 83
1

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 }

Ajain Vivek
  • 1,111
  • 1
  • 12
  • 20