Angular 4 get queryString

2019-07-26 07:15发布

问题:

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:

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.