Angular 7 带有 GET 参数的路由器路径

Angular 7 router path with GET parameter

我已经搜索了几个小时,但找不到解决我问题的有效方法...

我的 angular 应用程序通过 GET 参数将用户重定向到 returns jwt 的 oAuth2 API。我发现了如何使用 angular 读取 GET 参数,但我的问题是另一回事:

{path: 'authenticate', component: AuthenticationComponent}

这是我为 AuthenticationComponent 设置的路由。它在没有任何其他参数的情况下按预期工作,但使用单个获取参数('/authenticate?jwt=123' 而不是 '/authenticate')它不再工作并且我的'**'路由被激活。

一个变通方法是另一个网站(不是写在 angular 中)将用户重定向到 angular 页面并将 GET 参数转换为 URL 参数('/authenticate ?jwt=123' => '/authenticate/123') 并将我的路由路径更改为 'authenticate/:jwt' 但我想用我的 angular 应用程序来做。

请帮帮我

尝试在这样的路由中使用匹配器 { component: AuthenticateComponent, matcher: authenticate} 和 authenticate 是这样的函数

function authenticate(url: UrlSegment[]) {
    return url[0].path=="authenticate"?{consumed: url}: null;
}

这将匹配到 AuthenticateComponent 的路由,并且在组件中您可以获得这样的 jwt this.route.snapshot.queryParams['jwt']。希望这有帮助。

如果您像这样注入 Router as a dependency, you'll need to navigate

this.router.navigate( ['authenticate'], { queryParams: { jwt: '123'}});

或者,如果您使用的是 routerLink,请按如下方式使用:

<a [routerLink]="['/authenticate']" [queryParams]="{ jwt: '123'}">Authenticate</a>

Here's a Working Sample StackBlitz for your ref.

像这样设置路由器

{path: 'authenticate/:jwt', component: AuthenticationComponent}

并获取组件中的jwt值

// top component
import { Router, ActivatedRoute } from '@angular/router';
// constructor arg
constructor(private route: ActivatedRoute) {}
// user method or ngOnInit inside
this.route.params['value'].jwt

你的模块中的下一个导入路由模块

// top module
import { RouterModule } from '@angular/router';
// import object
imports: [RouterModule.forRoot([])]

工作正常