Angular 5.x正则路由问题:编辑路由无法跳转求助
Angular 5.x路由重定向外部链接无响应的问题分析与解决
我来帮你拆解下这个问题,你遇到的核心问题和对应的解决方案如下:
问题根源
你在路由里用redirectTo: 'http://google.com'来跳转到外部网站,但Angular的redirectTo属性仅支持内部路由路径跳转,它会把外部URL当成内部路由的一部分去解析,自然不会触发浏览器的外部跳转,所以才会出现“无任何响应”的情况。
另外也可以顺便检查下你的GuidMatcher是否正确匹配了/vacancies/{guid}/edit的父路由部分——不过如果是匹配问题,通常会出现404或者路由报错,而你说的是“无响应”,所以核心问题还是外部跳转的写法不对。
解决方案
要实现外部网站跳转,你不能直接用redirectTo,得用以下两种方式之一:
方案1:使用路由守卫(CanActivate)
创建一个专门处理外部跳转的守卫,在守卫里执行浏览器跳转:
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class ExternalRedirectGuard implements CanActivate { canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { // 执行外部跳转 window.location.href = 'http://google.com'; // 返回false阻止当前路由激活 return false; } }
然后修改你的路由配置,把原来的redirectTo替换成使用这个守卫:
const routes: Routes = [ { path: 'vacancies', canActivateChild: [AuthGuard], component: VacanciesContainer, children: [ { path: '', component: VacanciesComponent }, { path: 'create', component: VacancyCreateComponent }, { path: 'archived', children: [ { path: '', component: ArchivedVacanciesComponent }, { matcher: GuidMatcher, component: VacancyCardComponent } ]}, { matcher: GuidMatcher, children: [ { path: '', component: VacancyCardComponent }, // 用守卫处理外部跳转,组件可以填任意已声明的组件(因为守卫会提前跳转) { path: 'edit', canActivate: [ExternalRedirectGuard], component: VacancyCardComponent } ]} ] } ];
方案2:使用空组件处理跳转
如果不想用守卫,可以创建一个空组件,在组件初始化时执行外部跳转:
import { Component, OnInit } from '@angular/core'; @Component({ template: '' // 空模板 }) export class ExternalRedirectComponent implements OnInit { ngOnInit(): void { window.location.href = 'http://google.com'; } }
然后更新路由配置:
{ matcher: GuidMatcher, children: [ { path: '', component: VacancyCardComponent }, { path: 'edit', component: ExternalRedirectComponent } ]}
额外检查点
可以在你的GuidMatcher方法里添加日志输出,确认当访问/vacancies/{guid}/edit时,父路由的matcher是否被正确触发,确保路由匹配的层级是正确的。
内容的提问来源于stack exchange,提问作者AlexTGM
相关产品推荐
相关产品推荐

