Subscribing to query string parameters in Angular

Viewed 18794

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?

5 Answers

It works for me...

let comp = this;
ngOnInit(): void {
this.route.queryParams.subscribe(queryParams => {
  comp.a = queryParams['a'];
  comp.b = queryParams['b'];
});
  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);
    });
  }
Related