Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve hash fragment from url with Angular2

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

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

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

Router config:

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

])

like image 395
MFB Avatar asked Apr 16 '16 14:04

MFB


2 Answers

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)
    })
  }
}
like image 57
Ismail H Avatar answered Oct 14 '22 23:10

Ismail H


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 ActivatedRoute doesn't seem to handle that natively.

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 URLSearchParams object with the fragment to query for its values:

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.from converts URLSearchParams into an array of arrays that looks like: [['key', 'value'], ...]. Then lodash's _.fromPairs converts this to an object.

like image 19
nwayve Avatar answered Oct 14 '22 23:10

nwayve