Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribing to query string parameters in Angular

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?

like image 331
Remotec Avatar asked Aug 08 '17 10:08

Remotec


People also ask

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.

Can we pass object in query params in Angular?

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.


2 Answers

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?

like image 87
Vijayendra Mudigal Avatar answered Oct 14 '22 18:10

Vijayendra Mudigal


  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);
    });
  }
like image 20
Shawn Pivonka Avatar answered Oct 14 '22 18:10

Shawn Pivonka