1

Making an angular onboarding page for a corporate website. People will navigate to the page via a link in a welcome email which will contain a user specific token. I need to get this token out of the url querystring and use it in all ajax calls for auth purposes. My problem is reading the querystring.

Angular version is 4.2.4

I have combed through pages of docs on the '@angular/common' Location, LocationStrategy, PathLocationStrategy and have copy pasted the import and adding them to the providers, I get error after error after error. I can't find a simple example anywhere of importing location and using it to get the querystring from the page url. If this were javascript it's a super simple couple lines of code. Why is this so difficult? Any help would be greatly appreciated!

What I tried:

app.module.ts

import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';

providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}],

page.services.ts

constructor(private location: Location) {
  console.log('location: ', location);
}

1 Answer 1

7

You can do this using Angular's ActivatedRoute in the @angular/router package. Import it into your module as you do with the others, and inject it into your component as you already are with Location. Then you can access the queryParamMap like:

constructor(private route: ActivatedRoute) {
  console.log(route.snapshot.queryParamMap);
}

That will return a ParamMap interface, which was actually inspired by URLSearchParams interface :)

You can do things like route.queryParamMap.get('myQueryParam') and it works as you would expect.

Sign up to request clarification or add additional context in comments.

5 Comments

Let me know if this answers your question or if you need more information.
That was great! Thanks. Hadn't even noticed that option.
For Angular 6, I get null back for my parameter, as there are no parameters.
This answer may be obsolete. At least since v10, queryParamMap has been an Observable.
In regard to the update from @JohnChurchill here, the instant value is available from ActivatedRouteSnapshot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.