【问题标题】:Retrieve hash fragment from url with Angular2使用Angular2从url中检索哈希片段
【发布时间】:2016-08-08 11:51:41
【问题描述】:

鉴于此 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

])

【问题讨论】:

    标签: typescript angular2-routing


    【解决方案1】:

    我试过了,但快照是一个空字符串。 https://stackoverflow.com/a/51286916/569302

    这对我有用:

      ngOnInit(): void {
        this.route.fragment.subscribe({ 
            next: value => {
            if (value === null) {
              throw new Error('not implemented');
            }
            const access_token = new URLSearchParams(value).get('access_token')
            console.log({access_token})
          }
        });
      }
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案3】:

        假设您在构造函数中使用 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"}
        

        【讨论】:

          【解决方案4】:

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

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

          【讨论】:

            【解决方案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));
            

            【讨论】:

            • 请注意,如果您有 OAuth2.0 访问令牌,它们可以包含 +,这将成为您的访问令牌中的空白字符。
            【解决方案6】:

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

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

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

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

            【讨论】:

            • 找到this.route.fragment获取片段后的下一步是搜索如何解析其查询。感谢您添加URLSearchParamssn-p!
            • 很好的答案!我能够抓住片段,但我留下了多个参数来解析。您的回答为我节省了大量时间!
            【解决方案7】:

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

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

            【讨论】:

            • @MochamadArifin 我认为这正是您所需要的。
            • 太棒了,这是最简单的解决方案,谢谢:)
            【解决方案8】:

            对于那些仍在寻找的人:

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

            【讨论】:

            • 无需担心unsubscribing from ActivatedRoute observables: > ActivatedRoute 及其 observables 与 Router 本身是绝缘的。当不再需要路由组件并且注入的 ActivatedRoute 随之消亡时,Router 会销毁它。
            【解决方案9】:

            通过使用response_type=token 请求 OAuth 服务器并重定向到 %REDIRECT_URI%#access_token=:access_token&token_type=:token_type&expires_in=:expires_in,我遇到了同样的问题。

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

            我用这个配置修复了它:

            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
            ]);
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2010-12-29
              • 2017-05-30
              • 1970-01-01
              • 2011-05-11
              • 2014-01-02
              • 1970-01-01
              • 2011-01-20
              相关资源
              最近更新 更多