使用Angular2从URL检索哈希片段

MFB*_*MFB 30 typescript angular2-routing

鉴于这个url结构(我无法控制),如何使用Angular2检索哈希片段?

http://your-redirect-uri#access_token=ACCESS-TOKEN

我的路由器确实路由到正确的组件,但是一切都oauth被废弃后我无法在request.params或location.path中找到哈希片段.注定?

路由器配置:

@RouteConfig([
{path: '/welcome', name: 'Welcome', component: WelcomeComponent, useAsDefault: true},
{path: '/landing/oauth', name: 'Landing', component: LandingComponent}  // this one
Run Code Online (Sandbox Code Playgroud)

])

Ism*_*l H 41

对于那些仍在寻找:

import { ActivatedRoute } from '@angular/router';

export class MyComponent {

  constructor(
    private route: ActivatedRoute,
  ) { }

  myfunction(){
    this.route.fragment.subscribe((fragment: string) => {
        console.log("My hash fragment is here => ", fragment)
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 无需担心 [取消订阅 ActivatedRoute observables](https://angular.io/guide/router#observable-parammap-and-component-reuse):> ActivatedRoute 及其 observables 与路由器本身绝缘。当不再需要路由组件并且注入的 ActivatedRoute 随之消失时,路由器会销毁路由组件。 (6认同)

nwa*_*yve 11

为了扩展当前的答案,我想解决一种简单的方法来解析哈希中的查询参数(特别是对于联合响应),因为ActivatedRoute它似乎本身并不处理.

this.route.fragment.subscribe(fragment => {
  const response = _.fromPairs(Array.from(new URLSearchParams(fragment)));
  response.access_token;
  response.id_token;
  response.expires_in;
  response.token_type;
});
Run Code Online (Sandbox Code Playgroud)

首先使用片段创建一个新的URLSearchParams对象以查询其值:

new URLSearchParams(fragment).get('access_token');
Run Code Online (Sandbox Code Playgroud)

对于大多数情况,这可能是所有需要的,但如果需要Array.from将其转换URLSearchParams为对象,则转换为数组数组,如下所示:[['key', 'value'], ...].然后lodash _.fromPairs将其转换为对象.


小智 9

您还可以使用ActivatedRouteSnapshot而无需订阅其上的所有更改。

@Component({templateUrl:'./my-component.html'})
class MyComponent {
  constructor(route: ActivatedRoute) {
    const fragment: string = route.snapshot.fragment;
  }
}
Run Code Online (Sandbox Code Playgroud)


bee*_*man 5

我从 nwayve 那里得到了评论,并使用 RxJS 管道实现了它,如下所示:

this.route.fragment
  .pipe(
    map(fragment => new URLSearchParams(fragment)),
    map(params => ({
      access_token: params.get('access_token'),
      id_token: params.get('id_token'),
      error: params.get('error'),
    }))
  )
  .subscribe(res => console.log('', res));
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您有 OAuth2.0 访问令牌,它们可以包含“+”,它将成为访问令牌中的空白字符。 (2认同)