Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 routing - redirectTo with skipLocationChange

I have some routing module with its main path being set as: /canvas

const canvasRoutes: Routes = [
    {
        path: "canvas", component: CanvasComponent
    }
];

@NgModule({
    imports: [
        RouterModule.forChild(canvasRoutes)
    ],
    exports: [
        RouterModule
    ],
    declarations: [],
    providers: []
})
export class CanvasRoutingModule {
}

In the application routing module I would like to have the redirection path set to the /canvas every time the root path is accessed. Currently the configuration looks as follows:

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 to the http://localhost:4201 is being redirected to the http://localhost:4201/canvas.

However, I do not want to have the /canvas path appended to the url after redirection. How can this be achieved? Is there for example a way, that I could apply the skipLocationChange parameter to this redirection as I am using it with the router.navigate(... {skipLocationChange: true})?

like image 522
Kamil Chaber Avatar asked May 22 '17 09:05

Kamil Chaber


2 Answers

I have resolved that problem by subscribing to the router.events in the AppComponent and manually navigating to the canvas path 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})
                }
            }
        });
    }
}
like image 193
Kamil Chaber Avatar answered Nov 13 '22 16:11

Kamil Chaber


A little bit late, but maybe it's helpful:

I had the same problem and managed to solve it by adding ExtraOptions when declaring Router.forRoot

Like this:

imports: [ RouterModule.forRoot(routes, { initialNavigation : false }) ],

With this you avoid the initial navigation that sets /canvas to the URL.

After that you can continue using skipLocationChange.

Hope this helps!

like image 38
Aisatora Avatar answered Nov 13 '22 18:11

Aisatora