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

Ben*_*Ben 6 angular2-routing angular angular-router

角度版本:4

LoginComponent(位于public/signin路径中)登录后,我想要TestComponent在路径中导航public/test.我这样做如下:this._router.navigate(['public/test']) 然后,它正确地重定向但问题是它不会LoginComponent从DOM中删除(尽管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});
Run Code Online (Sandbox Code Playgroud)

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

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

export const routing = RouterModule.forChild(routes);
Run Code Online (Sandbox Code Playgroud)

Hoa*_* Ba 5

我有同样的问题。我通过在路由之前添加它来修复:

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


小智 0

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

最后我在我的组件中实现了 OnDestroy (来自核心)。当 ngOnDestroy 函数被调用时,我编写了一些 JavaScript 来从 DOM 中删除剩余元素。

var parent = document.getElementsByTagName("parent-name");
var child = document.getElementsByTagName("ng-component");
parent[0].removeChild(child[0]);
Run Code Online (Sandbox Code Playgroud)

我知道这只是一种临时解决办法,但也许足够好,直到您从某人那里得到最终答案。

希望