【问题标题】:Angular2 redirectTo causing URL params to be lost before canActivate calledAngular2 redirectTo 在调用 canActivate 之前导致 URL 参数丢失
【发布时间】:2017-03-22 07:55:09
【问题描述】:

我有一个 canActivate Guard,它检查 URL 中的 jwt 令牌并将其保存为 cookie(随后将检查 cookie)。如果没有令牌,则页面将重定向到另一个允许用户登录并创建 jwt 的应用程序。

当我向后导航时,我会得到一个类似的 URL:

http://localhost:3000/?jwt=...

AppModule 执行以下操作:

RouterModule.forRoot([{path: "**", redirectTo: "/import", pathMatch: "full"}], {useHash: true})

然后在ImportModule:

RouterModule.forChild([
            { path: "import", component: ImportComponent, canActivate: [ImportGuard] }
        ])

问题是我可以看到 URL 从 localhost:3000/?jwt=... 更改为 localhost:3000/#/import 并且参数丢失了,所以当我检查它时它不存在。

我是 Angular2 的新手,几乎可以肯定做错了什么,但我正在努力寻找任何关于如何从外部 URL 获取参数的示例。

我无法更改外部服务以返回 URL /#/import?jwt=...,并且我觉得我不需要这样做,因为当前的实现已经与 ReactJS 一起工作,所以我觉得应该可以使用角度。

有什么建议吗?如果您需要更多信息,请告诉我。

谢谢

【问题讨论】:

    标签: angular


    【解决方案1】:

    为什么不能在导入下使用子路由。例如

      RouterModule.forChild([
         { path: "import", component: ImportComponent, canActivate:[ImportGuard],
         Children:[
                 { path: "/:jwt", component: ImportComponent, canActivate: [ImportGuard]}] }
                ])
    

    【讨论】:

    • 此时RouterModule.forRoot...重定向参数已经丢失。感谢您的建议。
    【解决方案2】:

    我偶然发现了同样的问题,如何保留 url 参数并使用路由配置进行重定向。
    要绕过这个不受支持的操作,这可能会有所帮助:

    export const routes: Routes = [
      {
        path: '',
        component: RedirectComponent,
        pathMatch: 'full'
      }
     }, [... your other routes config]
     ];
    

    并且 RedirectComponent 已经在初始化:

    this.router.navigate(['/import'], {relativeTo: this.route , preserveQueryParams : true});
    

    【讨论】:

    • 我之前会尝试@Vignesh 的回答。
    • 我不知道为什么,但由于某种原因,当我尝试这个时,参数似乎仍然丢失了。或者,如果 URL 带有参数,它不会被识别为 document.URL 的参数,但 this.route.queryParams 不显示任何参数。
    • 尝试订阅 Observable.combineLatest(this.route.params, this.route.queryParams, (params, qparams) => ({ params, qparams }));
    【解决方案3】:

    我已经通过以下操作解决了这个问题

    RouterModule.forRoot([{path: "**", component: AppComponent, pathMatch: "full"}], {useHash: true})

    然后在 AppComponent 中,我使用 document.URL 获取 URL 并直接从字符串中获取参数。我不喜欢这个解决方案,因为它有点 hacky,更愿意使用 Route/Router。

    【讨论】:

      猜你喜欢
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 2021-09-13
      • 2017-10-23
      • 2017-03-13
      • 2010-11-19
      • 1970-01-01
      相关资源
      最近更新 更多