[英]Angular 4 routing - redirectTo with skipLocationChange
I have some routing module with its main path being set as: /canvas
我有一些路由模块,其主路径设置为:
/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. 在应用程序路由模块中,我希望每次访问根路径时都将重定向路径设置为
/canvas
。 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
. 它正常工作,并且对
http://localhost:4201
的访问被重定向到http://localhost:4201/canvas
。
However, I do not want to have the /canvas
path appended to the url after redirection. 但是,我不希望在重定向后将
/canvas
路径附加到URL。 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})
? 有没有例如一种方法,我可以将
skipLocationChange
参数应用于此重定向,因为我将它与router.navigate(... {skipLocationChange: true})
?
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. 我已经通过订阅
router.events
中的AppComponent
并手动导航到skipLocationChange
设置为true的canvas
路径来解决了这个问题。
@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})
}
}
});
}
}
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 我有同样的问题,并设法通过在声明Router.forRoot时添加ExtraOptions来解决它
Like this: 像这样:
imports: [ RouterModule.forRoot(routes, { initialNavigation : false }) ],
With this you avoid the initial navigation that sets /canvas to the URL. 通过这种方式,您可以避免将/ canvas设置为URL的初始导航。
After that you can continue using skipLocationChange. 之后,您可以继续使用skipLocationChange。
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.