Angular 4 routing - redirectTo with skipLocationChange

旧巷老猫 提交于 2019-11-30 04:37:41

问题


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!



来源:https://stackoverflow.com/questions/44109731/angular-4-routing-redirectto-with-skiplocationchange

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!