Angular 4 路由 - 使用 skipLocationChange 的 redirectTo

9

我有一些路由模块,其主路径设置为:/canvas

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

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

在应用程序路由模块中,我希望每次访问根路径时重定向路径设置为/canvas。当前配置如下:
const appRoutes: Routes = [
    {
        path: "", redirectTo: "/canvas", pathMatch: "full"
    }
];

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ],
    exports: [
        RouterModule
    ],
    declarations: [],
    providers: []
})
export class AppRoutingModule {

}

它可以正常工作,并且访问 http://localhost:4201 会被重定向到 http://localhost:4201/canvas

然而,我不想在重定向后的URL中附加 /canvas 路径。如何实现这一点?例如,我是否可以像在 router.navigate(... {skipLocationChange: true}) 中使用的那样应用 skipLocationChange 参数来进行重定向?


那么,你为什么要尝试重定向呢?使用 path: "", component: CanvasComponentpath: "", component: XXX, children: [{path: "", component: CanvasComponent}] 不已经足够了吗? - ulubeyn
在我看来,它不会那么清晰明了。在我的代码的其他部分中,我正在使用routerLink='/canvas'将其路由到画布组件。如果我将其更改为routerLink='',该语句将变得不清晰。 - Kamil Chaber
2个回答

12

我已经通过在AppComponent中订阅router.events并手动导航到具有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})
                }
            }
        });
    }
}

真的有必要订阅事件吗?如果您只将这一行放入构造函数中,是否就足够了:this.router.navigate(["canvas"], {skipLocationChange: true}); 在我看来,这应该是足够的。此外,您可以避免在每个NavigationStart事件中(不必要地)测试根URL! - John Archer

6
有点晚,但可能会有所帮助:
我之前遇到了同样的问题,成功解决了它。具体做法是在声明Router.forRoot时添加ExtraOptions,如下所示:
imports: [ RouterModule.forRoot(routes, { initialNavigation : false }) ],

使用此方法,您可以避免初始导航将/canvas设置为URL。

之后,您可以继续使用skipLocationChange。

希望这有所帮助!


这应该被标记为正确答案。谢谢! - Clark
这不应该被标记为正确答案,因为[legacy_disabledlegacy_enabledtruefalse]不支持作为有效值(https://github.com/angular/angular/commit/c4becca0e4238640461c43567a6d3e16b8c5d3f3)。 - Alexis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接