Angular 4 routing - redirectTo with skipLocationCh

2020-03-02 07:12发布

问题:

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})?

回答1:

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})
                }
            }
        });
    }
}


回答2:

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!