How to retrieve parameters from URL fragment in An

2020-06-22 04:35发布

问题:

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?

回答1:

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.



回答2:

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.



标签: angular oauth