如果另一个解析器调用然后重定向到不同的路径,则防止解析器进行额外的调用

问题描述 投票:0回答:1

我的应用程序尝试从“/”自动重定向用户以更正其他路径。为此,我们需要请求一些数据,然后才决定将用户重定向到哪里。选项只有几个,确定重定向的逻辑也很简单。

问题在于目的地之一必须请求相同的数据(调用相同的端点)。这是因为用户可以更深入,做一些事情然后返回。或者“侧身”然后返回。换句话说,返回该路线而不经过“/”。

我当前的设置大致如下

路由


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 时,只有一个调用(显然没有重定向)。

那么问题是如何跳过第二次通话?

我已经尝试过:

  • 使用状态进行导航 - 这很有希望,但状态在解析器中不可用
  • navigationId - 这也很有希望,我希望 / 有 navId==0 和 /users/orgs 0 或 1,具体取决于它是否被重定向。我想也许 navId > 0 会起作用。但实际上,navId 为 1 或 2,有时甚至为 null。
  • 取决于路由数据 - 重定向后不可用(可能在树中)
angular router angular-resolver
1个回答
0
投票

我的理解是,当导航发生时,您需要检查 API 调用并执行重定向,这听起来像是路由器事件的完美工作!

您可以在AppComponent(root)中添加此代码

ngOnInit()

router.events.subscribe(event:Event => {
    if(event instanceof NavigationEnd) {
        // perform API call here for redirect!
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.