本文介绍了Angular 4路由-redirectTo与skipLocationChange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 {
}

在应用程序路由模块中,我希望每次访问根路径时都将重定向路径设置为 /canvas.目前配置如下:

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 {

}

它工作正常,对 http://localhost:4201 的访问被重定向到 http://localhost:4201/canvas.

It works correctly and access to the http://localhost:4201 is being redirected to the http://localhost:4201/canvas.

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

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

推荐答案

我已经通过订阅 AppComponent 中的 router.events 并手动导航到canvas 路径,其中 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.

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

这篇关于Angular 4路由-redirectTo与skipLocationChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:46