【问题标题】:Angular 4 routing - redirectTo with skipLocationChangeAngular 4路由-redirectTo与skipLocationChange
【发布时间】:2017-10-21 22:13:56
【问题描述】:

我有一些路由模块,其主路径设置为:/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

但是,我不希望在重定向后将 /canvas 路径附加到 url。如何做到这一点?例如,有没有一种方法可以将 skipLocationChange 参数应用于此重定向,因为我将它与 router.navigate(... {skipLocationChange: true}) 一起使用?

【问题讨论】:

  • 那么,您为什么要尝试重定向?这还不够用path: "", component: CanvasComponentpath: "", component: XXX, children: [{path: "", component: CanvasComponent}]吗?
  • 在我看来,它的描述性不会那么清楚。在我的代码的其他一些部分,我使用 routerLink='/canvas' 路由到画布组件。如果我将其更改为routerLink='',则声明将变得不清楚。

标签: angular routing


【解决方案1】:

有点晚了,但也许有帮助:

我遇到了同样的问题,并设法通过在声明 Router.forRoot 时添加 ExtraOptions 来解决它

像这样:

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

这样可以避免将 /canvas 设置为 URL 的初始导航。

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

希望这会有所帮助!

【讨论】:

  • 这应该被标记为正确答案。谢谢!
【解决方案2】:

我已经通过订阅AppComponent 中的router.events 并手动导航到canvas 路径并将skipLocationChange 设置为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})
                }
            }
        });
    }
}

【讨论】:

  • 真的有必要订阅活动吗?如果您将这一行放入构造函数中还不够:this.router.navigate(["canvas"], {skipLocationChange: true});恕我直言,这应该足够了。此外,您(不必要地)在 every NavigationStart 事件中测试根 url 的事实!
猜你喜欢
  • 2019-09-15
  • 2017-01-25
  • 1970-01-01
  • 2021-11-05
  • 2017-06-04
  • 2018-10-02
  • 2018-01-13
  • 2021-02-20
  • 1970-01-01
相关资源
最近更新 更多