【问题标题】:Angular 8 routing rewrite failsAngular 8 路由重写失败
【发布时间】:2019-11-05 17:23:37
【问题描述】:

我有一个使用 MSAL.js 进行 Azure B2C 身份验证的应用。因此,它遵循常规的 OAuth 2.0 隐式流程来验证用户 - 当用户单击登录按钮时,它会被重定向到“授权”端点,然后用户在成功登录后被重定向回应用程序。

问题来了——回复请求如下:

https://localhost:4200/run#state=dc81c410-4cbd-4218-bc78-9c5b5e9bebe5&client_info={...}

为了使其正常工作,我必须将此 Url 重写为 run/state,因此生成的 Url 将是:

https://localhost:4200/run/state=f5f2c20f-ed72-4631-b834-80bf60aa6cd7&client_info={...}

这是在AppComponent.ngInit:

    this.router.events.subscribe(event => {
      if (event instanceof NavigationStart) {
        if (!!event.url && event.url.match(/^\/run#state/)) {
          const newUrl = event.url.replace("run#state", "run/state");
          console.warn(`newUrl = ${newUrl}`);
          this.router.navigate([newUrl]);
        }
      }
    });

现在我在日志中看到了重写。

但问题是它现在重定向到根目录。来自日志:

  • NavigationStartrun/state
  • URL REWRITE(但这次已经没有什么可重写的了,现在是 run/state
  • “Angular 正在开发模式下运行。调用 enableProdMode() 以启用生产模式。”
  • “处理来自重定向响应的回调” - MSAL.js callback function
  • “CHECK USER” - 来自 CanLoad 守卫(现在只是返回 true
  • RouteConfigLoadStart
  • 导航到https://localhost:4200/ BOOM!!!

为什么它会重定向到根目录?

一件重要的事情 - 如果我导航到:

https://localhost:4200/run/state=04e49903-1510-47da-9b24-cee988229d16&client_info={...}

在浏览器中,它确实打开了该路由(没有重定向!)。

repo 是on github

控制台:

【问题讨论】:

  • 您是否在您的某个路由模块中为/run/state 配置了路由?如果是这样,它是用于组件还是redirectTo
  • 是的,我愿意。它是一个组件。
  • 看起来它在 CheckUser 之后立即路由到 root。你确定路由守卫在canLoad的所有场景下都返回true
  • 是的,只是return true; 行。
  • 添加了回购链接

标签: angular angular-routing msal


【解决方案1】:
  • 如果你需要在路由/状态上路由(重写)你应该试试这个,

    this.router.events.subscribe(event => { if (event instanceof NavigationStart) { if (!!event.url && event.url.match(/^\/run#state/)) { this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => this.router.navigate(['/run/state'])); } } }); 我希望它对你有用

【讨论】:

  • 试过了。结果相同。
猜你喜欢
  • 1970-01-01
  • 2018-03-24
  • 2020-02-25
  • 2019-09-11
  • 2020-05-24
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多