角4获取queryString [英] Angular 4 get queryString

查看:82
本文介绍了角4获取queryString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为公司网站制作一个有角度的入门页面.人们将通过欢迎电子邮件中的链接导航到页面,该电子邮件将包含用户特定的令牌.我需要从url查询字符串中获取此令牌,并将其用于身份验证的所有ajax调用中.我的问题是读取查询字符串.

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版本是4.2.4

Angular version is 4.2.4

我在'@ angular/common'位置,LocationStrategy,PathLocationStrategy上浏览了文档页面,并复制粘贴了导入并将其添加到提供程序中,但遇到一个又一个错误.我找不到在任何位置导入位置并使用它来从页面url获取查询字符串的简单示例.如果这是javascript,那是几行简单的代码.为什么这么难?任何帮助将不胜感激!

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!

我尝试过的事情:

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);
}

推荐答案

您可以使用Angular的 @angular/router软件包中.与其他方法一样,将其导入到模块中,然后像使用Location一样将其注入到组件中.然后,您可以像这样访问queryParamMap:

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);
}

这将返回一个 ParamMap 界面,该界面实际上是受URLSearchParams界面的启发:)

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

您可以执行route.queryParamMap.get('myQueryParam')之类的操作,并且可以按预期工作.

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

这篇关于角4获取queryString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆