Hikaru Shindo
Hikaru Shindo

Reputation: 2913

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

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.

Upvotes: 10

Views: 11850

Answers (3)

Andro Sid
Andro Sid

Reputation: 19

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']);
                });

Upvotes: 0

Andro Sid
Andro Sid

Reputation: 19

try change this:

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

to this:

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

Upvotes: 1

BHAVYA BHUSHAN
BHAVYA BHUSHAN

Reputation: 114

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!!!

Upvotes: 7

Related Questions