Sometimes, we want to get query params from URL in Angular.
In this article, we’ll look at how to get query params from URL in Angular.
How to get query params from URL in Angular?
To get query params from URL in Angular, we can call the this.activatedRoute.queryParams.subscribe
method.
For instance, we write
import { Router, ActivatedRoute, Params } from "@angular/router";
import { OnInit, Component } from "@angular/core";
@Component({
//...
})
export class MyComponent implements OnInit {
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.queryParams.subscribe((params) => {
const userId = params["userId"];
console.log(userId);
});
}
}
to call this.activatedRoute.queryParams.subscribe
with a callback that gets the query parameters.
The callback is called whenever the query parameters change.
And we get the query parameter with the key as we did by using the userId
key to get the value of the userId
query parameter.
Conclusion
To get query params from URL in Angular, we can call the this.activatedRoute.queryParams.subscribe
method.