skip to Main Content

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.

7

Answers


  1. Chosen as BEST ANSWER

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

  2. did you tried this?

    import { Params, Router } from '@angular/router';
    
    
         constructor(private router: Router) {
    
                this.route.params.forEach((params: Params) => {
                //here you can get your params
                let param = params['parameterName'];
    
    
                })
            }
    
    Login or Signup to reply.
  3. 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});
    
    Login or Signup to reply.
  4. using Javascript :

    (new URL(location)).searchParams.get("parameter_name")
    
    Login or Signup to reply.
  5. 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 );
    
    Login or Signup to reply.
  6. This works for me! 🙂

    import { ActivatedRoute } from '@angular/router'; 
    
    constructor(private route: ActivatedRoute) { }
    
    /** usage in the method */
    let projectId = this.route.snapshot.queryParams.projectId;
    
    Login or Signup to reply.
  7. Check my answer in this post.

    [UPDATE]
    It seems some moderator has deleted my answer saying it was duplicate answer. But I disagree, as I posted relevant code snippets based on each question. Until this answer is not undeleted, I am posting the part of answer here again. if you agree, please vote to undelete my answer.


    Use window.location.hash to access to all parameters starting from #.
    Or you can use window.location.href to access full URL.
    To get the token you can use window.location.hash.match(/#access_token=([^&]+)/)[1].

    Note: If you are using TypeScript then you’d need to import window in your component.

    declare let window;
    

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search