1

Here is the URL that I want to handle http://localhost/?id=120&lang=en&search=abc

How can I read these parameters (id, lang and search).

Devx
  • 41
  • 1
  • 3

2 Answers2

0

You have to use ActivatedRoute from @angular/router, just like any other parameters, no difference with a not-optionnal one.

more info at : https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters

Alexis Le Gal
  • 327
  • 4
  • 11
  • Thank you for your answer. But while importing ActivatedRoute it is showing an compile time error that Module '"/var/www/public/node_modules/@angular/router/index"' has no exported member 'ActivatedRoute'. – Devx Aug 29 '16 at 10:00
  • You didn't specify what version, ActivatedRoute is only available in RC5, – John Baird Aug 29 '16 at 10:16
  • How can I get this in RC1? – Devx Aug 29 '16 at 11:03
0
export class HeroComponent implements OnInit {
  constructor(private _activatedRoute: ActivatedRoute, private _router:Router) {
    _router.routerState.queryParams.subscribe(
      data => console.log('queryParams', data['st']));

See also Get route query params

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I guess for the final release it's ActivatedRoute instead. However how would one get an optional parameter ? e.g. If `lang` is set pet querystring, use it, else fall back to english. As far as I can see, there is no way to know for sure that the current subscription is done for this page, meaning if it's not present it will just wait forever. (RxJs timeouts maybe?) – Suau Nov 14 '16 at 11:35
  • You can just subscribe to `route.queryParams()`. AFAIK the callback passed to `subscribe()` will be called on every route change, just `data['someId']` will return `null` when no `?someid=value` or `;someid=value` was present on the route. – Günter Zöchbauer Nov 14 '16 at 12:01
  • Thanks a lot, that was useful! – Suau Nov 14 '16 at 12:13
  • `route.queryParams()` seems to be only called when there is a change in the query part. For example lets say I'm having a url `/cats/:page?pagesize=x` if I navigate to the next page, but didn't change the pagesize, the callback won't be called. That's a problem when I have `route.params` and `route.queryParams` and want to call a rest API depending on both. Usually I'd zip them together, but if my 'callback' for `route.queryParams` might or might not get called, then I'd still need a timeout. – Suau Nov 21 '16 at 08:59
  • You could report it as a bug or you subscribe to `router.events` (http://stackoverflow.com/questions/35912932/angular-2-router-event-listener/35912966#35912966) and read the values from `_activatedRoute.routerState`. AFAIR there is also an issue that the values are only available after a timeout (sorry don't remember exactly) I think that's a known issue with an open ticket. – Günter Zöchbauer Nov 21 '16 at 09:02