角度路由器以编程方式导航时,旧组件保留在dom中

时间:2017-08-08 10:40:49

标签: angular angular2-routing angular-router

Angular版本:4

LoginComponent(位于public/signin路线登录后,我想导航到路径TestComponent中的public/test。 我是这样做的:this._router.navigate(['public/test']) 然后,它正确地重定向,但问题是它不会从DOM中删除LoginComponent(尽管ngOnDestroy会被调用)。

值得一提的是,导航到TestComonent使用 <a routerLink='/public/test'>Test</a>按预期工作。

我做错了什么?

app.routing.ts:

const APP_ROUTES:Routes = [
  {path: 'public', loadChildren: './authentication/authentication.module#AuthenticationModule'}
];

export const APP_ROUTING:ModuleWithProviders = RouterModule.forRoot(
APP_ROUTES, {
useHash: false, enableTracing: true, initialNavigation: true});

` authentication.routing.ts(这两个组件都属于):

const routes: Routes = [
    {
        path: '',
        children: [
            {path: 'test', component: TestComponent},
            {path: 'signin', component: LoginComponent},
        ]
    }
];

export const routing = RouterModule.forChild(routes);

3 个答案:

答案 0 :(得分:1)

我有同样的问题。 我在路由之前添加了这个修复:

this.zone.run(() => {
    // Your router is here
    this._router.navigate(['public/test'])
});

答案 1 :(得分:0)

我遇到了和你一样的问题,并找到了(临时的)解决方法。 首先我认为这是模块上延迟加载的路由问题,我改为处理组件,但问题永远不会消失。

最后,我在我的组件中实现了OnDestroy(来自核心)。 当调用ngOnDestroy函数时,我写了一个小的javascript,从DOM中删除了rest元素。

var parent = document.getElementsByTagName("parent-name");
var child = document.getElementsByTagName("ng-component");
parent[0].removeChild(child[0]);

我知道这只是一个暂时的工作,但也许还不错,直到你得到一个人的最终答案。

希望

答案 2 :(得分:0)

您是否尝试在开头添加斜杠以使其与路由器链接完全匹配?

this._router.navigate(['/public/test'])

以下是有关路线中相对路径与绝对路径的更多信息:https://angular.io/guide/router#relative-navigation