【发布时间】:2018-04-15 16:26:01
【问题描述】:
再次需要帮助!
我正在使用 Angular 4,并希望从我的组件中的 url 获取参数。网址为“http://myhost/index?user=James&token=123&picture=3456abc.png”或“http://myhost/index?user=Peter”
我尝试了这些不同的方法,但没有运气。
如何获取url参数'user'、'token'和'picture'?
import { Routes, RouterModule, Router, ActivatedRoute, RouteSegment, Params, ROUTER_DIRECTIVES } from '@angular/router';
constructor(private restSvc: RestSvc, private router: Router, private domSanitizer: DomSanitizer,
private mdIconRegistry: MdIconRegistry, private activatedRoute: ActivatedRoute, private routeSegment: RouteSegment) {
// Method 1: subscribe to queryParamMap - not working - all values are undefined
/* this.activatedRoute.queryParamMap.subscribe(params => {
this.userName = params['user'];
this.userToken = params['token'];
this.userPicture = params['picture'];
}) */
// Method 2: use the $location service - not working
//var params = $location.search('user', 'token', 'picture'); //syntax error - cannot find name $location
// Method 3: RouteSegment
this.userName = routeSegment.getParam('user'); // Error: compile eror - has no exported member 'RouteSegment'.
console.log("App Component Constructor - params user [" + this.userName + "]");
}
--- 已解决-----------------
我尝试过激活路由的方法,但没有奏效。最后,我回到 Rach 建议的基本内容。现在可以了。我试图解析的 url 不是来自 route.navigate。这是来自我的服务器的重定向。不确定是否重要。
吸取的教训:有时候,回归基础是好的,即简单地通过 & 和 = 解析 location.href 字符串以获取参数。
【问题讨论】:
-
您是如何浏览页面的?显示“导航代码”和完整网址。
标签: angular typescript