Angular 4 routing - redirectTo with skipLocationChange
I have a routing module whose main path is set as: /canvas
const canvasRoutes: Routes = [
{
path: "canvas", component: CanvasComponent
}
];
@NgModule({
imports: [
RouterModule.forChild(canvasRoutes)
],
exports: [
RouterModule
],
declarations: [],
providers: []
})
export class CanvasRoutingModule {
}
In the routing module of the application, I would like the redirect path to be set /canvas
every time the root path is accessed. The configuration currently looks like this:
const appRoutes: Routes = [
{
path: "", redirectTo: "/canvas", pathMatch: "full"
}
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
],
declarations: [],
providers: []
})
export class AppRoutingModule {
}
It works correctly and access is http://localhost:4201
redirected to http://localhost:4201/canvas
.
However, I don't want the /canvas
URL path to be added after the redirect . How can this be achieved? For example, is there a way that I can apply a parameter skipLocationChange
to this redirect as I am using it with router.navigate(... {skipLocationChange: true})
?
source to share
I solved this problem by subscribing to router.events
in AppComponent
and manually following the path canvas
with skipLocationChange
set to true.
@Component({
...
})
export class AppComponent {
constructor(private router: Router) {
this.router.events.subscribe(routerEvent => {
if (routerEvent instanceof NavigationStart) {
if (routerEvent.url == "/") {
this.router.navigate(["canvas"], {skipLocationChange: true})
}
}
});
}
}
source to share
A bit late, but maybe useful:
I had the same problem and managed to solve it by adding ExtraOptions while declaring Router.forRoot
Like this:
imports: [ RouterModule.forRoot(routes, { initialNavigation : false }) ],
By doing this, you avoid the initial navigation, which sets / canvas to the URL.
After that, you can continue using skipLocationChange.
Hope this helps!
source to share