router.navigate is not working (Angular6, lazy loading)

被刻印的时光 ゝ 提交于 2020-08-22 11:46:13

问题


I'm a newbie for Angular 4+ (currently using v.6). I've been trying to use this.router.navigate(['/landing']) function to redirect from login component to landing component, it's not working properly. It will show the landing page for a sec then redirect back to login page again.

But if I try to navigate through a normal link, for example,

<a routerLink="/landing">landing</a>

It work properly.

Here is my app-routing.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'login',
    loadChildren: './login/login.module#LoginModule'
  },
  {
    path: 'landing',
    loadChildren: './landing/landing.module#LandingModule'
  },
  {
    path: '',
    redirectTo: 'landing',
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: 'landing',
    pathMatch: 'full'
  }
];

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

And here is the code in the login component,

export class LoginComponent implements OnInit {

  constructor(private router: Router) { }

  ngOnInit() {
  }

  login(){
    this.router.navigate(['/landing']);
  }
  
}

Here is the code in landing-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { LandingComponent } from './landing.component';

const routes: Routes = [
  {
    path:'', component: LandingComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class LandingRoutingModule { }

Thanks for helps.


回答1:


I faced similar issue, how I resolved it:

In Component.ts

constructor(private router: Router, private route: ActivatedRoute){}

this.router.navigate(['../landing'], {relativeTo: this.route})

try this and let me know if it helps!!!




回答2:


try change this:

{
  path: 'login',
  loadChildren: './login/login.module#LoginModule'
}

to this:

{
  path: 'login',
  loadChildren: () => LoginModule
}



回答3:


But my best solution is this:

add to constructor:

constructor(private readonly loader: NgModuleFactoryLoader)

then only after loading module itself you should call navigate:

 this.loader.load(./login/login.module#LoginModule)
                .then(factory => {
                    this.router.navigate(['/landing']);
                });


来源:https://stackoverflow.com/questions/50414225/router-navigate-is-not-working-angular6-lazy-loading

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!