I've seen quite a few examples of subscribing to query string parameters in Angular 2+ but I can't seem to get it to work
e.g. How get query params from url in angular2?
Here is my code:
import { ActivatedRoute, Router } from '@angular/router';
...
export class MyComponent implements OnInit,OnDestroy {
private a: boolean = true;
private b: boolean = true;
constructor(route: ActivatedRoute) {
...
ngOnInit(): void {
this.route.queryParams.subscribe((queryParams:any) => {
this.a = queryParams.a;
this.b = queryParams.b;
});
The problem I have is that this
does not appear to refer to my component to setting a
and b
which I want to use to drive *ngIf
statements does not work.
What am I doing wrong?
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.
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.
queryParams property accepts object as a value. To pass multiple query parameters to router. navigate we can construct an object with list of parametrs and pass it on to queryParams . For example to display books under category fiction and orderby price, use the below code snippet.
The below code is for Angular 5.
import { ActivatedRoute, Router } from '@angular/router';
...
export class MyComponent implements OnInit, OnDestroy {
private a: boolean;
private b: boolean;
constructor(private route: ActivatedRoute) {
this.a = true;
this.b = true;
...
}
ngOnInit(): void {
this.route.queryParams.subscribe(queryParams => {
this.a = queryParams['a'];
this.b = queryParams['b'];
});
Could you try and check if it works?
ngOnInit() {
// Example http://google.com?foo=bar#hash
this.route.fragment.subscribe(frag => {
// Result: 'hash'
console.log('Fragment: ', frag);
});
this.route.queryParamMap.subscribe(queryParams => {
/**
* result: 'bar'
*/
console.log('Data: ', queryParams);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With