Angular Cannot read property 'navigate' of undefined

Viewed 2829

I encountered the error when I hit "/home" url:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'navigate' of undefined
TypeError: Cannot read property 'navigate' of undefined
    at onAuthRequired (main.js:83)
    at OktaAuthGuard.<anonymous> (vendor.js:77444)

when I use trying to use OktaAuthGuard and customized onAuthRequired function:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {HomeComponent} from './home/home.component';
import {OktaCallbackComponent, OktaAuthGuard } from '@okta/okta-angular';
import { LoginComponent } from './login.component';

export function onAuthRequired({oktaAuth, router }) {
  // Redirect the user to your custom login page
  router.navigate(['/login']);
}

const routes: Routes = [
  {path: '', redirectTo: '/home', pathMatch: 'full', canActivate: [OktaAuthGuard], data: {
      onAuthRequired
    }
  },
  {path: 'home', component: HomeComponent, canActivate: [OktaAuthGuard], data: {
      onAuthRequired
    }
  },
  {path: 'login', component: LoginComponent },
  {path: 'callback', component: OktaCallbackComponent }
];

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

Actually, I used the same snippet of code for my another project, it didn't throw error, but here Why this cause the error?

I am using Spring boot as the backend.

2 Answers

you need to get the Router service via the injector:

  // Use injector to access any service available within your application
  const router = injector.get(Router);

so in your function it would give:

export function onAuthRequired(oktaAuth, injector) {
  const router = injector.get(Router);
  router.navigate(['/login']);
}

the full example is here: https://github.com/okta/okta-angular#using-a-custom-login-page

of course, 'router' is undefined because it is not declared, you must inject it into the constructor:

import { Router } from '@angular/router';
//.....
  constructor(private router: Router) {}
// then you can use 
this.router.navigate(['/login']);
Related