angular 4 如何获取url参数

标签 angular typescript

再次需要帮助!

我正在使用 Angular 4 并希望从我的组件中的 url 获取参数。 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 + "]");
  }

--- 已解决 ------------------------------

我尝试过 activatedRoute 方法,但没有用。最后,我回到 Rach 建议的基础。现在可以了。我试图解析的 url 不是来自 route.navigate。这是来 self 的服务器的重定向。不确定是否重要。

经验教训:有时候,回到基础是很好的,即简单地通过 & 和 = 解析 location.href 字符串来获取参数。

最佳答案

首先,在您的构造函数中设置ActivatedRoute

constructor(private route: ActivatedRoute){}
public user:your_type;

其次,将此代码放入构造函数回调中:

this.route.params.subscribe(params => { this.user = params['user']; });

如果您使用以下代码重定向,此方法将起作用:

this.router.navigate(['./yourlocation', { user: this.user }]);

已修改

Angular Url 结构是 a/:paras1/:paras2a?a=3; 而不使用 &

如果你使用&来分隔你的参数,建议使用nativeJS来获取。

constructor(){
  this.user = this.getUrlParameter('user');
}

public user;
private getUrlParameter(sParam) {
  return decodeURIComponent(window.location.search.substring(1)).split('&')
   .map((v) => { return v.split("=") })
   .filter((v) => { return (v[0] === sParam) ? true : false })
   .reduce((prev, curv, index, array) => { return curv[1]; }, undefined); 
};

关于angular 4 如何获取url参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47087285/

相关文章:

reactjs - TypeScript + React <- 传递 props

javascript - 无法从 Chrome 控制台看到变量,但可以在代码中访问

javascript - 无法从路径导入 IonicModule

node.js - ionic - 关于版本的困惑

angular - 如何使用 angular dart webdev 在 localhost 上建立安全连接?

angular - 无法使用生产构建导入 Angular MockBackend

javascript - 将 ES6 与 Angular2 rc3 一起使用时需要未捕获的反射元数据垫片

typescript - 通过keyof映射type->type,类似于string->type

angular - Angular 2 中的语法高亮显示

angular - 强制 Angular 2 View 从数据更新