vadjs
vadjs

Reputation: 355

Angular 2. How to get queryParams in component?

I have task - to transmit some params in App component of Angular 2 application through URL.

The best way i found to do it - using queryParams. But i not found best way to parse these params.

I'm sure that using ActivatedRoute will solve my task (and i know how to import it and how to use in constructor) but i'm not sure how to extract queryParams using it.

Can you help me in it?

Unfortunately i couldn't run my code in plunker(couldn't find properly example on Angular 2), attaching it as is.

import {Component} from '@angular/core';
import { ActivatedRoute, NavigationExtras } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
  selector: 'my-app',
  styles: [],
  template: 
  `
  <button (click)="testLink()">Make link</button>
  <button (click)="checkEntity()">Check Params</button>
  `
})
export class App {
  entity: any;

  constructor(
    private route: ActivatedRoute) {
  }

  ngOnInit() {

  }

  checkEntity(){
    this.entity = this.route
      .queryParams
      .map(params => params['entity'] || 'None');

    if(this.entity) alert('It works!');
  }

  testLink(){
    let navigationExtras: NavigationExtras = {
      queryParams: { 'entity': 'user' }
    };

    this.router.navigate(['/'], navigationExtras);
  }
}

Last step - to get queryParams in entity. This code using Observable but for me will be enough single check.

Upvotes: 1

Views: 1629

Answers (1)

aRealPerson
aRealPerson

Reputation: 371

I am passing parameters in my ionic 4 app like this. All that is missing in the code is to:

  1. subscribe to the observable when retrieving
  2. stringify the query parameters when passing
    export class App {
      entity: any;
      constructor(private route: ActivatedRoute) { }

      checkEntity() {
        this.route.queryParams.subscribe(params => { 
          if (params) {
            if (params.entity) {
              alert('It works!'); 
            } 
          } 
        })
      }

      testLink() {
        let navigationExtras: NavigationExtras = { 
          queryParams: { 
            entity: JSON.stringify('user') 
          } 
        };
        this.router.navigate(['/'], navigationExtras);
      }
    }

Upvotes: 2

Related Questions