0

I have implemented ActivatedRoute on my app.component.ts page. This is the page where I have a big, red exit button on, and it appears on all pages of my app as intended.

I jump into the url I've created (with a query string) as follows:

http://localhost:4200/status?returnString=xyz

I have a private route: ActivatedRoute within my constructor. In my ngOnInit() function I have console.log(this.route.queryParams);. And that returns an object where the ._value is an object with a property of returnString: "xyz" as intended.

The problem is, when I console.log(this.route.queryParams.returnString) or console.log(this.route.queryParams._value) I am being served an object with no properties. {}.

My question is, what happened or moreover, what am I doing wrong? What will it take for me to get a parameter from the URL that I can consume in Angular 5?

Vinnie Saletto
  • 329
  • 2
  • 5
  • 20

2 Answers2

2

The problem you're having is due to the fact that queryParams is an Observable.

In your ngOnInit() function you need to subscribe to the observable:

ngOnInit() {
    this.route. queryParams.subscribe(
      params => {//Do something with the params.returnString},
      err => console.log(err)
);
}

Official Angular Docs - ActivatedRoute

Narm
  • 10,677
  • 5
  • 41
  • 54
1

queryParams is an Observable, so you should listen to changes instead of inspecting the value.

When app.component is initiated the value isn't set yet, but when you inspect it, it is. That's probably what you are experiencing.

Set up a listener and react to changes instead

route.queryParams.subscribe((params: Params) => this.doSomething(params.returnString))
Patrick
  • 17,669
  • 6
  • 70
  • 85