typescript 使用 Angular2 从 url 中检索哈希片段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36665234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:04:27  来源:igfitidea点击:

Retrieve hash fragment from url with Angular2

typescriptangular2-routing

提问by MFB

Given this url structure (over which I have no control), how can I retrieve the hash fragment using Angular2?

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

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

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

My router does route to the correct component, but everything after oauthget scrapped and I can't find the hash fragment in request.params or location.path. Doomed??

我的路由器确实路由到了正确的组件,但是在oauth报废后的所有内容都无法在 request.params 或 location.path 中找到哈希片段。注定??

Router config:

路由器配置:

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

])

])

回答by Ismail H

For those still looking :

对于那些仍在寻找的人:

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)
    })
  }
}

回答by nwayve

To expand on the current answers, I wanted to address an easy way to parse the query params in the hash (specifically for a federated response) since the ActivatedRoutedoesn't seem to handle that natively.

为了扩展当前的答案,我想解决一个简单的方法来解析散列中的查询参数(特别是对于联合响应),因为它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;
});

First create a new URLSearchParamsobject with the fragment to query for its values:

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

new URLSearchParams(fragment).get('access_token');

For most cases this is probably all that is needed, but if converting this to an object is desired, Array.fromconverts URLSearchParamsinto an array of arrays that looks like: [['key', 'value'], ...]. Then lodash's _.fromPairsconverts this to an object.

在大多数情况下这可能是所有需要的,但如果此转换为一个对象是期望的,Array.from转换URLSearchParams成一个数组的数组,看起来像:[['key', 'value'], ...]。然后 lodash_.fromPairs将其转换为一个对象。

回答by Aya Azzam

you can also use ActivatedRouteSnapshotwith no need to subscribe for all changes on it.

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

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

回答by beeman

I've taken the comment from nwayve and implemented it using RxJS pipes like this:

我从 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));

回答by Tecayehuatl

Assuming you're using ActivatedRouteclass in your constructor, try this:

假设您在构造函数中使用ActivatedRoute类,请尝试以下操作:

let params = this.route.snapshot.fragment;

const data = JSON.parse(
    '{"' +
        decodeURI(params)
            .replace(/"/g, '\"')
            .replace(/&/g, '","')
            .replace(/=/g, '":"') +
        '"}'
);

console.log(data); // { json: "with your properties"}

回答by Pinguet62

I had the same problem by requesting OAuth server with response_type=token, and who redirects to %REDIRECT_URI%#access_token=:access_token&token_type=:token_type&expires_in=:expires_in.

我通过使用response_type=请求 OAuth 服务器token以及谁重定向到%REDIRECT_URI%#access_token=:access_token&token_type=:token_type&expires_in=:expires_in.

The problem is, by default, the direct access to sub-url is not routed: in your case, %BASE_URL%/landing/oauthwill not be redirect to LandingComponentcomponent.

问题是,默认情况下,不会路由对 sub-url 的直接访问:在您的情况下,%BASE_URL%/landing/oauth不会重定向到LandingComponent组件。

I fixed it with this configuration:

我用这个配置修复了它:

import { bootstrap } from '@angular/platform-browser-dynamic';
import { provide } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { ROUTER_PROVIDERS } from '@angular/router';

import { AppComponent } from './components/app/app.component';

bootstrap(AppComponent, [
    ROUTER_PROVIDERS,
    provide(APP_BASE_HREF, { useValue: '/' }) // this line
]);

回答by Sameer Basil

An option for parsing the fragment data with plain javascript is

使用纯 javascript 解析片段数据的一个选项是

this.activatedRoute.fragment.subscribe(value => {
  let fragments = value.split('&')
  let fragment = {}
  fragments.forEach(x => {
    let y = x.split('=')
    fragment[y[0]] = y[1]
  })
})

The information will be in the form of an object which can be easily accessed.

该信息将采用易于访问的对象形式。

回答by Drenai

You can retrieve the url fragment at any time using the following code - which makes use of the Routerservice:

您可以随时使用以下代码检索 url 片段 - 这使用了该Router服务:

const urlTree = this.router.parseUrl(this.router.url);
console.log(urlTree.fragment); //access_token=ACCESS-TOKEN