我的应用程序尝试从“/”自动重定向用户以更正其他路径。为此,我们需要请求一些数据,然后才决定将用户重定向到哪里。选项只有几个,确定重定向的逻辑也很简单。
问题在于目的地之一必须请求相同的数据(调用相同的端点)。这是因为用户可以更深入,做一些事情然后返回。或者“侧身”然后返回。换句话说,返回该路线而不经过“/”。
我当前的设置大致如下
路由
const routes: Routes = [
{
path: '',
component: PagesComponent,
resolve: {
initialDataResolver,
},
children: [
{
path: '',
component: RedirectComponent, // subscribe to route.data and make redirects
},
],
}
...
{
path: '',
component: PagesComponent,
children: [
{
path: UserPath.Root,
// here we have loadChildren and module, but for the sake of brevity I put just the relevant bit as children
children: [
{
path: 'user/organisations',
resolve: {
initialDataResolver,
},
component: UserOrganisationsComponent,
}
],
},
],
},
通过此设置,转到“/”的用户将经历呼叫、重定向,然后再次呼叫。 当直接转到 /users/organization 时,只有一个调用(显然没有重定向)。
那么问题是如何跳过第二次通话?
我已经尝试过:
我的理解是,当导航发生时,您需要检查 API 调用并执行重定向,这听起来像是路由器事件的完美工作!
您可以在AppComponent(root)中添加此代码
ngOnInit()
router.events.subscribe(event:Event => {
if(event instanceof NavigationEnd) {
// perform API call here for redirect!
}
});