5

Example

http://localhost:4200/login?aUasas129198

resolves to

http://localhost:4200/login

What should I do if I want the value after '?'

I tried doing

{ path: 'login/:id', component: LoginComponent },

But it did not work

I also tried

console.log(this.route.snapshot.queryParams);
console.log(this.route.snapshot.params);

But they both return empty object. What should I do now please help

Sanjay Idpuganti
  • 312
  • 5
  • 11
  • Do you still see the query param in the url though? Doing `login/:id` makes id a `queryParam`. You should also be using `this.route.queryParams.subscribe(queryParams => console.log(queryParams))` Also, apparently there's no value of the queryParam that you're specifying. – SiddAjmera Sep 24 '18 at 09:54
  • No the query param disappears – Sanjay Idpuganti Sep 24 '18 at 09:56
  • No I can't the part after '?' comes from another solution and I need to interpret the data after '?'. I do not have any choice – Sanjay Idpuganti Sep 24 '18 at 09:58
  • Use `param` instead of a `queryParam` in that case. Also make sure to subscribe to `route.params` instead of using `route.snapshot.params` – SiddAjmera Sep 24 '18 at 10:00
  • subscribing to route.params returns empty object too – Sanjay Idpuganti Sep 24 '18 at 10:02

2 Answers2

2

Actually, You are not passing the value in any key:

http://localhost:4200/login?aUasas129198

The proper way should be:

http://localhost:4200/login?anykey=aUasas129198
// get it as
// this._ActivatedRoute.queryParams.subscribe()

If you are using the URI as you shown in your question as:

{ path: 'login/:id', component: LoginComponent }

Then you should pass the value to id as:

http://localhost:4200/login/aUasas129198
// remember the '/' after the login that you didn't use.
// get it as
// this._ActivatedRoute.snapshot.params.id
Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34
2

If it’s unavoidable that Angular redirects you immediately and loses the query parameters, you could subscribe to router events and on each NavigationStart for login route get a hold of route’s queryParamMap or snapshot.paramMap before they’re lost in redirection, then you can e.g. pass it to a service and do whatever you wanted to do with it.

Or, as another alternative, you could look into configuring your router with queryParamsHandling: 'preserve', in which case it should pass the query params to the next route (see the section in Angular docs linked below for more on this).

I worked with a project that made use of query params in Angular 5, IIRC I don’t think it would redirect on its own so I’d recommend to look elsewhere in your project but I may be wrong.

See also

Anton Strogonoff
  • 32,294
  • 8
  • 53
  • 61