Angular无法读取未定义的属性'navigate'>>

问题描述 投票:2回答:2

当我点击“ / 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)

当我尝试使用OktaAuthGuard

和自定义的[[onAuthRequired函数时: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 { }
实际上,我在另一个项目中使用了相同的代码片段,它没有引发错误,但是为什么会导致错误?

我正在使用Spring Boot作为后端。

当我按“ / home” url时遇到错误:错误错误:未捕获(承诺中):TypeError:无法读取未定义的属性'navigate'TypeError:无法读取未定义的属性'navigate'...
javascript angular spring-boot okta
2个回答
1
投票
您需要通过注入器获得路由器服务:

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


0
投票
当然,'router'是未定义的,因为未声明,必须将其注入到构造函数中:
© www.soinside.com 2019 - 2024. All rights reserved.