【问题标题】:angular 4 how to get url parameters角度4如何获取url参数
【发布时间】: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


【解决方案1】:

首先,在您的constructor 中设置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); 
};

【讨论】:

  • 嗨,Rach,非常感谢!请您帮忙检查您建议的代码。我在 .reduce((prev, curv, index, array) => { return curv[1]; }, undefined); 上遇到语法错误。抱歉我无法修复它。
  • /apps/fhir2_james/src/app/app.component.ts (46,15) 中的错误:类型参数 '(prev: string[], curv: string[], index: number , array: string[][]) => string' 不能分配给 '(previousValue: string[], currentValue: string[], currentIndex: number, array: string[][]) => str 类型的参数。 ...'。类型“字符串”不可分配给类型“字符串 []”。
  • 嗨Rach,你说得对,“如果你使用&来分隔你的参数,建议使用nativeJS来获取。”现在可以了。
  • 很高兴听到这个消息。
  • public getUrlParameter(sParam) { return decodeURIComponent(window.location.search.substring(1)).split('&') .map((v) => { return v.split(" =") }) .filter((v) => { return (v[0] === sParam) ? true : false }) .reduce((acc:any,curr:any) => { return curr[1 ]; },不明确的); };
【解决方案2】:

如果您想使用查询参数而不在路由中定义它们,您可以在构造函数中引用 ActivatedRoute 并订阅 queryParams。

constructor(private route: ActivatedRoute) {
    this.route
      .queryParams
      .subscribe(params => {
          // here you can access params['user'], params['token'], etc.
      });
}

【讨论】:

【解决方案3】:

如下例所示,使用 ActivatedRoute 快照。

this.userName = this.activatedRoute.snapshot.params['user'];
this.userToken = this.activatedRoute.snapshot.params['token'];
this.userPicture = this.activatedRoute.snapshot.params['picture'];

【讨论】:

  • 嗨,我需要定义那个路由,因为那些用户、令牌和图片只是参数吗?我以为我只需要定义站点/索引。 URL 是“hxxp://myhost/index?user=James&token=123&picture=3456abc.png”。非常感谢您的帮助!
  • 您好 i3lai3la,我尝试了您的代码,但仍然无法获取参数。会不会因为 url 是 Facebook OAuth 返回后来自我们服务器的重定向?因此,该 url 不是来自 Angular 导航,它是我的 Angular 应用程序的第一个初始 url。只是一个想法。
【解决方案4】:

想知道所有的url参数吗?

constructor(private activatedRoute: ActivatedRoute) {
    this.activatedRoute.params.subscribe((params: Params) => {
       console.log(params)
    })
}

在子路由中,需要使用parent获取父路由参数

this.activatedRoute.parent.params.subscribe((params: Params) => {
    console.log(params)
})

【讨论】:

    【解决方案5】:

    仔细检查以确保您正确定义了路线。

    在您的路线定义中,您应该有这样的内容:

    path: ':user/:id/:token/:picture'

    【讨论】:

    • 非常感谢您的帮助。请你看看我对“i3lai3la”的评论。我没有将路由定义为':user/:id/:token/:picture'。我将我的路线定义为仅站点/索引。
    【解决方案6】:

    获取 Angular 4 中的 url 参数 eg:http://localhost/doctor?test=1

    import {Component} from '@angular/core';
    import {Router} from '@angular/router';
    @Component({
      selector: 'app-root',
      templateUrl: './app.home.html',
    })
    
    export class HomeComponant {
    title = 'Home';
    
    
    constructor(
    
        private router: Router,
    
    ) {}
    
    onSubmit() {
      this.router.navigate(['/doctor'],{queryParams:{test:1}});
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      相关资源
      最近更新 更多