Reputation: 85
In my app i have following rows
@Component({
selector: 'sampleSelector',
template: `<router-outlet></router-outlet>`,
directives: [ROUTER_DIRECTIVES],
providers: [ROUTER_PROVIDERS, HTTP_PROVIDERS]
})
@RouteConfig([
{
path: '/...', name: 'Dashboard', component: DashboardCenterComponent, useAsDefault: true
}
])
export class AppComponent {
}
When i connect to /... it shows DashboardCenterComponent and it's ok. But the problem that when i redirect to any other page, for which i don't have any configured routes, it shows me blank screen.
Child route:
@RouteConfig([
{path: '/', name: 'DashboardMain', component: DashboardComponent, useAsDefault: true}
])
export class DashboardCenterComponent {
}
I need a mechanism that will redirect from non-existent route to root route.
For example i visit localhost:3000/hello and i don't have route for that. I need to redirect to localhost:3000. How to do that?
Upvotes: 2
Views: 2727
Reputation: 24945
router.recognize can rescue you
import {Router} from 'angular2/router';
import {Location} from 'angular2/platform/common';
@Component({
....
})
@RouteConfig([
....
])
export class AppComponent {
constructor(router: Router, location: Location){
router.subscribe(() => {
router.recognize(location.path()).then((instruction) => {
if(!instruction){
// this code will execute if there no route exists for the current url
router.navigate(['/DashboardMain']);
}
});
});
}
}
Update: added router subscription to check url on every navigation
Upvotes: 2
Reputation: 4524
In my app I have an ErrorComponent which I display when the route is wrong, but you can redirect on which component you want, something like :
{ path: '/*ErrorRoutes', name: 'NotFound', component: NotFoundComponent }
Which means config all the routes, but for anything else "/*" do that
Your code updated :
@Component({
selector: 'sampleSelector',
template: `<router-outlet></router-outlet>`,
directives: [ROUTER_DIRECTIVES],
providers: [ROUTER_PROVIDERS, HTTP_PROVIDERS]
})
@RouteConfig([
{
path: '/...', name: 'Dashboard', component: DashboardCenterComponent, useAsDefault: true
},
{ path: '/*NotFound', name: 'Dashboard', component: DashboardCenterComponent }
])
export class AppComponent {
}
Upvotes: 0