Angular 2 http.get with params

时间:2016-07-20 08:14:43

标签: angular typescript http

我想在GET请求中发送查询参数。我的班级看起来像这样:

 @Injectable()
 export class Loader implements TranslateLoader{
  constructor(private http: Http){
   }
   getTranslation(lang: string): Observable<any>
   {
     return this.http.get(routes.Localization.Get) ;// in that place I need to pass params
   }
 }

我该怎么做?

3 个答案:

答案 0 :(得分:41)

您可以利用URLSearchParams类:

getTranslation(lang: string): Observable<any> {
  let params = new URLSearchParams();
  params.set('param1', 'value1');

  return this.http.get(routes.Localization.Get, { search: params });
}

这将产生这样的URL(参数在查询字符串中添加):http://...?param1=value1

请参阅此课程的文档:

它现在提供对编码/解码参数的支持。

答案 1 :(得分:12)

这非常简单 - 您可以定义URLSearchParams并将其传递到http.get方法的第二个参数中:

import { URLSearchParams } from '@angular/http'

let params: URLSearchParams = new URLSearchParams();
params.set('param1', 'someValue');
params.set('param2', 'someValue');

return this.http.get(routes.Localization.Get, { search: params });

答案 2 :(得分:-8)

当这样的网址http://stackoverflow.com?param1=value

您可以通过以下代码获取param1:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';

@Component({
    selector: '',
    templateUrl: './abc.html',
    styleUrls: ['./abc.less']
})
export class AbcComponent implements OnInit {
    constructor(private route: ActivatedRoute) { }

    ngOnInit() {
        // get param
        let param1 = this.route.snapshot.queryParams["param1"];
    }
}