[英]Angular - Router Config - redirectTo using parameters/variable segment
在下面的示例路由配置中,我收到一个错误:无法重定向到'/ ip /:id'。 输入localhost:8080 \\ sso \\ ip \\ 1时找不到':id'。 我试图了解如何使用路径的可变段进行重定向。 在这种情况下,:id似乎找不到。 我引用了https://vsavkin.com/angular-router-understanding-redirects-2826177761fc ,它描述了一个类似的用例,其中在redirectTo属性中使用了动态段。
使用启动的/ sso / ip / :id路由中的:id参数可以解析id吗? 有人提出了类似的问题,但从未答复: https : //groups.google.com/forum/# ! topic/angular/Mw0N3qYphO8 。
非常感谢您的协助?
const appRoutes: Routes = [
{
path: 'ip',
children: [
{
path: ':id',
children: [
{
path: 'tcv',
component: IpTcvComponent
},
{
path: '',
component: IpComponent
}
]
},
{
path: '',
component: IpHomeComponent
}
]
},
{
path: 'sso',
children: [
{
path: 'ip',
children: [
{
path: ':id',
children: [
{
path: 'tcv',
pathMatch: 'full',
redirectTo: '/ip/:id/tcv'
},
{
path: '',
pathMatch: 'full',
redirectTo: '/ip/:id'
}
]
},
{
path: '',
pathMatch: 'full',
redirectTo: '/ip'
}
]
}
]
}
];
如果无法使路由配置正常工作,我的方法是手动处理重定向。 具有带有redirectInFlight()
方法的RedirectService
,该方法侦听可观察到的Router.events
。 当路由器尝试转到目标路径(例如/sso/ip/:id
,透明地重定向到正确的路径: /ip/:id
然后,我将服务添加到AppModule.providers
,将服务注入AppComponent
,并调用redirectInFlight()
AppComponent
@Component({
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
//inject the RedirectService
constructor(private redirectSvc:RedirectService){}
//start listening to the router and redirecting
ngOnInit() {this.redirectSvc.redirectInFlight();}
}
RedirectService
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import 'rxjs/Rx'; //replace with just the classes you need from RxJS library
@Injectable()
export class RedirectService {
events$:Observable<any>; //stream of Router events
constructor(private router:Router) {
this.events$ =
//listen to router events and inspect the `url` string property
//and filter for urls that begin with /sso
this.router.events.filter(e=> e.url && e.url.startsWith('/sso'))
}
redirectInFlight(){
//First remove /sso from the start of url to fix it
this.events$.map(e => e.url.replace('/sso',''))
//navigate to the fixed URL
.subscribe(newUrl=>this.router.navigateByUrl(newUrl));
}
}
最后,您可以从路由器配置中删除整个sso
路径及其子路径,从而大大简化了配置。
注意:此实现是一个起点。 您可以通过存储和引用重定向映射而不是对“ / sso”进行硬编码来使其更加健壮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.