angular 4如何获取url参数

Aut*_*run 6 typescript angular

再次需要帮助!

我正在使用Angular 4,并希望从我的组件中的url获取参数.URL是" http:// myhost/index?user = James&token = 123&picture = 3456abc.png "或" http:// myhost/index?user = Peter "

我试过这些不同的方法,但没有运气.

如何获取网址参数'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 + "]");
  }
Run Code Online (Sandbox Code Playgroud)

- - 解决 - - - - - - - - - - - - - - -

我尝试过activateRoute方法,但没有用.最后,我回到了Rach的基本建议.它现在有效.我尝试解析的url不是来自route.navigate.它是我服务器的重定向.不确定是否重要.

获得的经验:有时候,回到基础是很好的,即只需通过&和=解析location.href字符串来获取参数.

Rac*_*hen 10

首先,设置ActivatedRoute你的constructor

constructor(private route: ActivatedRoute){}
public user:your_type;
Run Code Online (Sandbox Code Playgroud)

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

this.route.params.subscribe(params => { this.user = params['user']; });
Run Code Online (Sandbox Code Playgroud)

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

this.router.navigate(['./yourlocation', { user: this.user }]);
Run Code Online (Sandbox Code Playgroud)

体改

角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); 
};
Run Code Online (Sandbox Code Playgroud)