m0_71786908 2024-05-23 10:03 采纳率: 66.7%
浏览 3

angular路由相关的一个问题,有没有人知道如何解决

我想通过链接 http//:localhost:4200/hello?abc=123 访问具有如下路由的angular应用,这个路径肯定是重定向到auth/server/login的,我想在路由守卫里获取一开始访问的这个链接http//:localhost:4200/hello?abc=123及其查询参数该怎么做

const routes: Routes = [
  {
    path: '',
    component: AppComponent,
    canActivate: [appGuard],
    children: [
      {
        path: 'pages',
        loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule)
      },
      {
        path: 'auth/server',
        loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule)
      },
      {
        path: '',
        redirectTo: 'auth/server/login',
        pathMatch: "full"
      }
    ]
  },
  {
    path: '**',
    pathMatch: "full",
    redirectTo: 'pages/not-found'
  }
];

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

  • 写回答

2条回答 默认 最新

  • 专家-赤兔[在线] 全栈领域优质创作者 2024-05-23 10:03
    关注

    引自免费微信小程序:皆我百晓生

    要实现你的需求,在Angular中,你可以使用路由守卫(Route Guard)来捕获初始请求并处理它。在这种情况下,你需要创建一个自定义的路由守卫来获取URL和查询参数,并根据这些信息决定是否执行重定向。

    首先,让我们创建一个名为CustomAuthGuard的自定义路由守卫:

    import { Injectable } from '@angular/core';
    import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    
    @Injectable({
      providedIn: 'root'
    })
    export class CustomAuthGuard implements CanActivate {
    
      constructor(private router: Router) {}
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Promise<boolean> | Observable<boolean> {
        const initialUrl = state.url;
        const queryParams = new URLSearchParams(state.queryParams);
    
        console.log('Initial URL:', initialUrl);
        console.log('Query Parameters:', queryParams.toString());
    
        // 在这里,你可以根据查询参数决定是否进行重定向
        if (queryParams.has('abc')) {
          console.log('Redirecting due to abc query parameter.');
          this.router.navigate(['auth/server/login'], { replaceUrl: true });
          return false; // 阻止默认的重定向行为
        }
    
        return true; // 如果不需要特殊处理,则允许继续导航
      }
    }
    

    然后将这个自定义路由守卫添加到你的主路由配置中,替换掉原来的'appGuard':

    import { CustomAuthGuard } from './custom-auth-guard.service'; // 引入自定义路由守卫
    
    // ...
    
    const routes: Routes = [
      {
        path: '',
        component: AppComponent,
        canActivate: [CustomAuthGuard], // 使用CustomAuthGuard
        children: [
          // ...
        ]
      },
      // ...
    ];
    

    这样,当用户尝试访问带有查询参数的URL时,CustomAuthGuard会拦截请求,打印出初始URL和查询参数。如果你需要根据查询参数进行特定操作,可以在canActivate方法中实现。在这个例子中,我们简单地检查是否存在名为'abc'的查询参数,并根据其存在与否决定是否重定向到'/auth/server/login'。

    注意:replaceUrl: true 参数用于替换历史记录中的URL,这样用户返回时不会看到原始URL。如果不想替换历史记录,可以将其设置为 false 或省略。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 5月23日

悬赏问题

  • ¥15 mmo能不能做客户端怪物
  • ¥15 osm下载到arcgis出错
  • ¥15 Dell g15 每次打开eiq portal后3分钟内自动退出
  • ¥200 使用python编写程序,采用socket方式获取网页实时刷新的数据,能定时print()出来就行。
  • ¥15 matlab如何根据图片中的公式绘制e和v的曲线图
  • ¥15 我想用Python(Django)+Vue搭建一个用户登录界面,但是在运行npm run serve时报错了如何解决?
  • ¥15 QQ邮箱过期怎么恢复?
  • ¥15 登录他人的vue项目显示服务器错误
  • ¥15 (标签-android|关键词-app)
  • ¥15 comsol仿真压阻传感器