问题描述
我想创建一个外部重定向,但为了使所有路由保持一致,我认为在路由器状态配置下执行所有操作(包括外部重定向)会很好.
I would like to create an external redirect, but to make all routes consistent I think it would be nice to do everything(including external redirects) under Router States configuration.
所以:
const appRoutes: Routes = [
{path: '', component: HomeComponent},
{path: 'first', component: FirstComponent},
{path: 'second', component: SecondComponent},
{path: 'external-link', /*would like to have redirect here*/}
];
UPD:并且我不想在这种情况下使用空组件,就像 @koningdavid 建议的那样.这个解决方案对我来说看起来很奇怪.对于这种情况,应该很容易实现,没有虚拟组件.
UPD: and I don't want to use empty component for this case like @koningdavid suggested. This solution looks really weird for me. It should be something really easy to implement for such case, without virtual components.
推荐答案
您可以通过使用路由的解析选项的技巧来实现您想要的.Resolve 是 Angular2 将为要初始化的路由获取的一些数据值.您可以在官方此处找到更多详细信息文档.
You can achieve what you want with a trick using the resolve option of a route. Resolve is some data value that Angular2 will obtain for the route to be initialized. More details you can find here in the official documentation.
我已经尝试过这种方法并且确实有效.示例:
I have tried this approach and it does work. Example:
将此添加到提供程序部分(并从路由中导入所需的类)
Add this to the provider section (plus import the required classes from Routing)
@NgModule({
providers: [
{
provide: 'externalUrlRedirectResolver',
useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) =>
{
window.location.href = (route.data as any).externalUrl;
}
}
]
})
然后你可以像这样定义你的路线:
Then you can define your route like this:
{
path: 'test',
component: AnyRandomComponent,
resolve: {
url: 'externalUrlRedirectResolver'
},
data: {
externalUrl: 'http://www.google.com'
}
}
这将重定向到外部 URL.这确实有点像黑客的方式.我试图在不使用组件的情况下实现结果,但是您必须使用 redirectTo
或 component
或 children
或 loadChildren代码>.
redirectTo
不会触发解析,我不确定孩子,但你可以尝试.
This will redirect to the external URL. It's a bit of a hackish way really. I tried to achieve the result without using the component at all, but you have to use either redirectTo
or component
or children
or loadChildren
. redirectTo
won't trigger the resolve and I am not sure about children, though you can experiment.
您可以在一个不错的类中实现它,而不是在提供程序中直接实现.文档中的更多信息(请参阅上面的参考资料).
You can implement it in a nice class rather than direct function in provider. More info in the documentation (see reference above).
附言我认为我真的宁愿自己使用重定向组件.只需使用数据的技巧并使用 externalUrl
从路由器获取状态即可将其作为参数.
P.S. I would really rather use a redirect component myself I think. Just use the trick with the data and getting the state from the router with externalUrl
to get this as a parameter.
这篇关于如何在不使用组件的情况下从 angular2 路由重定向到外部 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!