Angular 6的路由重定向不调用onInit()方法。
创始人
2024-10-16 07:30:50
0

问题描述: 在Angular 6中,当路由重定向时,组件的ngOnInit()方法不会被调用。

解决方法: 可以使用Angular的路由守卫来解决这个问题。路由守卫是一种用于保护路由的机制,它可以在路由导航过程中进行拦截和处理。

  1. 创建一个名为"AuthGuard"的路由守卫:
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router) {}

  canActivate(): Observable | Promise | boolean {
    // 在此处添加任何需要在路由重定向前执行的逻辑
    return true; // 或者根据需要返回false进行重定向
  }
}
  1. 在路由配置中使用路由守卫:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AuthGuard } from './auth.guard';

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
  // 其他路由配置
];

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

在上面的示例中,我们在"profile"路由上使用了AuthGuard路由守卫。这意味着只有在AuthGuard的canActivate()方法返回true时,才能访问"profile"组件。

通过这种方式,即使路由重定向,也可以确保在加载组件之前进行必要的逻辑处理。

相关内容

热门资讯

第二分钟辅助!wepoker好... 第二分钟辅助!wepoker好友助力码,wepoker透视辅助下载,指引教程(有挂助手)1、wepo...
六分钟辅助!wpk模拟器,hh... 六分钟辅助!wpk模拟器,hhpoker的辅助是真的吗,策略教程(新版有挂)1、hhpoker的辅助...
9分钟辅助!微扑克微乐辅助,w... 9分钟辅助!微扑克微乐辅助,wepoker私人局辅助器怎么用,指引教程(有挂方略)1、用户打开应用后...
第1分钟辅助!wepoker免... 第1分钟辅助!wepoker免费脚本咨询,hhpoker有没有作弊挂,举措教程(有挂实锤)1、起透看...
第十分钟辅助!cloudpok... 第十分钟辅助!cloudpoker作弊,wepoker模拟器哪个好用,大纲教程(了解有挂)1.wep...
第5分钟辅助!fishpoke... 第5分钟辅助!fishpoker透视,epoker透视,妙招教程(真是有挂)1、金币登录送、破产送、...
第九分钟辅助!wpk有那种辅助... 第九分钟辅助!wpk有那种辅助吗,wepoker私人局规律,窍门教程(有挂教学)亲,关键说明,wep...
第2分钟辅助!wepoker私... 第2分钟辅助!wepoker私人局辅助,wepoker作弊视频,举措教程(有挂技巧)1、第2分钟辅助...
第6分钟辅助!德普之星辅助器,... 第6分钟辅助!德普之星辅助器,德州透视插件,资料教程(有挂总结)1、在德普之星辅助器插件功能辅助器技...
第二分钟辅助!wepoker免... 第二分钟辅助!wepoker免费透视,wepoker免费透视,举措教程(有挂解密)1、许多玩家不知道...