Angular2 get url query parameters

46,193

Solution 1

Here is my final working code:

Imports:

import { Router, NavigationCancel } from '@angular/router';
import { URLSearchParams, } from '@angular/http';

Constructor:

 constructor(public router: Router) {
    router.events.subscribe(s => {
      if (s instanceof NavigationCancel) {
        let params = new URLSearchParams(s.url.split('#')[1]);
        let access_token = params.get('access_token');
        let code = params.get('code');
      }
    });
  }

Solution 2

You're looking for query parameters from ActivatedRoute.

To receive them, you could put them into your component's OnInit function like this:

private accesstoken;
private code;

constructor(private route: ActivatedRoute) { }

ngOnInit() {
  // Capture the access token and code
  this.route
      .queryParams
      .subscribe(params => {
          this.accesstoken = params['#access_token'];
          this.code = params['code'];
      });

  // do something with this.code and this.accesstoken
}

There's more examples in the link I put above. You may have problems with angular because the router also identifies fragments, which start with the #... If angular does identify it as a fragment, then you can just subscribe to the fragment observable from ActivatedRoute and do it that way.

I'm not sure if you're being redirected. If you are, the could look into using the preserveQueryParams navigation option, something like this.

this.router.navigate([redirect], {preserveQueryParams: true});

Solution 3

using Javascript :

(new URL(location)).searchParams.get("parameter_name")

Solution 4

getQueryParams( locationSearch: string):any {
    let params = {};
    if( locationSearch ) {
        locationSearch = locationSearch.split('?')[1];
        let splited = locationSearch.split('&');
        for( let i = 0; i < splited.length; i++ ) {
            let propName = splited[i].split('=')[0];
            let propValue = splited[i].split('=')[1];
            params[propName] = propValue;
        }
    }

    return params;
}

let q = getQueryParams( location.search );

Solution 5

This works for me! :)

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

constructor(private route: ActivatedRoute) { }

/** usage in the method */
let projectId = this.route.snapshot.queryParams.projectId;
Share:
46,193

Related videos on Youtube

Ben
Author by

Ben

I'm a game developer (Unity, BennuGD, Div Game Studio) I'm a professional web developer (Angular) I'm a professional mobile app developer (Xamarin Forms)

Updated on July 09, 2022

Comments

  • Ben
    Ben almost 2 years

    I'm setting up a Facebook registration for my Angular2 web app. Once the application accepted via Facebook (after being redirected to the Facebook authorization page), it redirect to my webapp with the token and code as url params:

    http://localhost:55976/?#access_token=MY_ACCESS_TOKEN&code=MY_CODE
    

    But once the page is loaded, the params are removed. The url become:

    http://localhost:55976/
    

    How can I extract the parameters (access_token and code) before they are removed? My routing configuration contains:

    { path: 'login', component: LoginComponent },
    { path: 'login/:access_token/:code', component: LoginComponent },
    

    EDIT:

    Here is how I redirect to facebook in my login.component: html:

    <a class="btn btn-social btn-facebook socialaccount_provider facebook" title="Facebook" href="#" (click)="login_facebook()">
        <span class="fa fa-facebook"></span> <span style="padding-left:25px">Sign in with Facebook</span>
    </a>
    

    Typescript:

    login_facebook() {
        let url = 'https://www.facebook.com/dialog/oauth?'+
            'client_id=my_client_id' +
            '&redirect_uri=' + encodeURIComponent('http://localhost:55976/#/login/') +
            '&response_type=code%20token';
        console.log(url);
        window.location.href = url;
    }
    

    The facebook api redirect to http://localhost:55976/#/login/, this is where I try to get the access_token and code parameters.

    EDIT 2:

    If I remove the sharp in the redirect url, facebook redirect me to the good URL, but without the sharp, angular cannot resolve the url.

    Before removing '#':

    redirect_uri: http://localhost:55976/#/login/
    facebook return: http://localhost:55976/?#access_token=MY_ACCESS_TOKEN&code=MY_CODE
    

    After removing '#':

    redirect_uri: http://localhost:55976/login/
    facebook return: http://localhost:55976/login/?#access_token=MY_ACCESS_TOKEN&code=MY_CODE
    

    That mean that the problem comes from the sharp. But without the sharp, angular returns HTTP Error 404.0 - Not Found.

  • Ben
    Ben over 7 years
    Thank you for your reply. The this.route.params variable is empty. When I try to log it with console.log(JSON.stringify(params)); it returns '{}'
  • Ben
    Ben over 7 years
    Thank you for your reply. The params are still empty. I've tried with fragment observable from ActivatedRoute but it doesn't change anything. I'm not being redirected. The redirection is made by the facebook api. I have updated the main post to add more details.
  • Federico Pettinella
    Federico Pettinella over 7 years
    Hmmm. To me, it seems like if the problem might be that facebook is redirecting to localhost:55976/?#access_token=MY_ACCESS_TOKEN&code=MY_CODE while you want to redirect to localhost:55976/#/login/…. Maybe facebook is redirecting to the wrong component?
  • Ben
    Ben over 7 years
    Yes you are right, the problem seems to comes from the facebook redirection. I have updated my post. The problem know is the redirection without the '#'.
  • Federico Pettinella
    Federico Pettinella over 7 years
    You can change angular2 to work without the # by using the PathLocationStrategy instead of HashLocationStrategy. However the PathLocationStrategy is already the default in angular2 so you're probably overriding it somewhere. What does your main module look like where you're providing your routes? See here for more info.
  • Ben
    Ben over 7 years
    You are right, PathLocatinoStrategy was set to HashLocationStrategy. But when I set it to PathLocationStrategy, I get 404 errors every time I try to access a page with url (instead of navigating).
  • Ben
    Ben over 7 years
    Any idea why the hash is removed before I can access it?
  • Ben
    Ben over 7 years
    I have fixed my 404 error but now, when the login page is reached, the hash fragment is removed before I can access it. Any idea?
  • Denko Mancheski
    Denko Mancheski about 7 years
    Which location strategy are you using? I also have the problem that you have in the above comment: that the hash fragment is removed before I can access it.. did you manage this to work with hashlocationstrategy or it only works with html5 pathlocationstrategy?
  • Ben
    Ben about 7 years
    I'm using html5 pathlocationstrategy. I'm not sure but i think it only works with this strategy.
  • Denko Mancheski
    Denko Mancheski about 7 years
    Yep, I confirm, this only works with the pathlocationstrategy
  • Marcus
    Marcus almost 7 years
    +1 for correct answer. I usually hold myself from ranting but this is the right answer I suppose and yeah, imagine that ... in pure JS it takes one row and in Angular it takes imports, subscribes, etc. Too much to do very little.
  • Rodrigo Assis
    Rodrigo Assis over 6 years
    this is almost perfect for me. but I'm getting this error when typescript is building: Argument of type 'Location' is not assignable to parameter of type 'string'
  • Christoph Lütjen
    Christoph Lütjen over 6 years
    URL constructor expects a string as first parameter but location is a Location. new URL(location.href) will work.
  • hubert17
    hubert17 about 6 years
    For you guys having timing headaches in Observables.