Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve parameters from URL fragment in Angular application?

Tags:

angular

oauth

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?

like image 673
user183101 Avatar asked Nov 07 '17 09:11

user183101


People also ask

How do you query parameters in a URL?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.

How do I get query parameters in Angular 10?

Use queryParamMap to access query parameters. Another way to access query paramters in Angular is to use queryParamMap property of ActivatedRoute class, which returns an observable with a paramMap object. Take an example of above URL with multiple parameters.

What is Queryparam in Angular?

The query parameters feature in Angular lets you pass the optional parameters while navigating from one route to another. When you pass a query parameter to a specific route, it looks something like this, http://localhost:4200/orders? category=watches.


1 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.

like image 57
Boulboulouboule Avatar answered Sep 28 '22 17:09

Boulboulouboule