How to retrieve parameters from URL fragment in Angular application?

Viewed 9614

I use OAuth Implicit flow authentication method in my Angular application. To retrieve access token I need to parse parameters from following string:

http://localhost/authentication#access_token={0}&expires_in={1}&user_id={2}

After some investigation I did not find any mechanisms to retrieve parameters from such URLs (all mechanisms which I found are based on using manual string splitting. Does it mean that Angular doesn't have "out of the box" mechanisms to parse parameters from URL fragment and the best way to do this is use substring() or split() method?

4 Answers

You can do it using the ActivatedRoute :

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    console.log(this.route.snapshot.fragment); // only update on component creation
    this.route.fragment.subscribe(
      (fragments) => console.log(fragments)
    ); // update on all changes
  }

To retrieve query parameters, just replace fragment by queryParams on this code.

constructor(private activatedRoute: ActivatedRoute) {

    const fragment = activatedRoute.snapshot.fragment;

    const parts = fragment.split('&');

    const params = parts.reduce((map, part) => {
        const pieces = part.split('=');
        map[pieces[0]] = pieces[1];
        return map;
    }, {});

    console.log(params);
}

Maybe it's a bit late, but could help someone in the same situation

With this code you should be able to retrieve the params pretty straightforward

this.activatedRoute.fragment.subscribe((fragment: string) => {
    const urlParams = new URLSearchParams(fragment);
    const accessToken = urlParams.get("access_token")
})
import {Router, ActivatedRoute, Params} from '@angular/router';
import {OnInit, Component} from '@angular/core';

@Component({...})
export class MyComponent implements OnInit {

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    // subscribe to router event
    this.activatedRoute.params.subscribe((params: Params) => {
        let userId = params['user_id'];
        console.log(userId);
      });
  }

}

If you want to get the query parameters, replace this.activatedRoute.params with this.activatedRoute.queryParams.

Related