Angular 4 get queryString

别等时光非礼了梦想. 提交于 2019-12-11 07:26:25

问题


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.



来源:https://stackoverflow.com/questions/48508226/angular-4-get-querystring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!