Rolando
Rolando

Reputation: 62596

How to get route parameters from a url in angular2 app?

I have a constant ROUTES that is set up like this:

export const ROUTES: Routes = [
    { path: 'custom', component: MyCustomComponent }
]

I want to make it so that if the user goes to:

http://my-angular-app/#/custom/something?mode=CRAZY

That within "MyCustomComponent", I can see access the "mode=CRAZY" and do something with it.

How do I access the variable "mode" from my MyCustomComponent? Or do I have to define a new route to be able to pass the parameters?

Upvotes: 2

Views: 847

Answers (2)

Giovane
Giovane

Reputation: 1451

As said in other answer, you may use ActivatedRoute.snapshot.queryParam but if your queryParam change it's value while you are in the same route you'll have problems if you need to update the value that you got from the queryParam. As you are in the same route angular won't recreate the component for, so you won't get the new value from the snapshot in your constructor. If you need to get the updated value while in the same route, you should subscribe to que queryParam observable.

constructor(
  private route: ActivatedRoute
) {
  this.route.queryParams.subscribe((queryParams) => {
    console.log(queryParams); // get the values of your queryParams
  });
}

Now, every new value on your queryParams will be updated in your Component. And as it is an Angular Observable you won't be bother to treat it's unsubscription manually, Angular'll take care of it for you.

Upvotes: 2

R. Richards
R. Richards

Reputation: 25141

This is what works for me to access the query parameters within a component.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent {

  constructor(private activatedRoute: ActivatedRoute) {
    let mode = activatedRoute.snapshot.queryParams['mode']; //< HERE
    console.log(mode);
  }    
}

You need to import the ActivatedRoute, and inject it via the constructor. Then you can access what comes in on the query string via the injected service.

With a router link like this:

<a [routerLink]="['/custom']" [queryParams]="{mode: 'CRAZY'}">Go There!</a>

The output from the console log is CRAZY.

Hope this helps.

Upvotes: 2

Related Questions