[英]Angular 2 http.get with params
I want to send query parameters within a GET request. 我想在GET请求中发送查询参数。 My class looks like this:
我的班级看起来像这样:
@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
}
}
How can I do this? 我怎样才能做到这一点?
You can leverage the URLSearchParams
class for this: 您可以利用
URLSearchParams
类:
getTranslation(lang: string): Observable<any> {
let params = new URLSearchParams();
params.set('param1', 'value1');
return this.http.get(routes.Localization.Get, { search: params });
}
This will result to an URL like this (parameters are added in the query string): http://...?param1=value1
. 这将产生这样的URL(参数在查询字符串中添加):
http://...?param1=value1
。
See the documentation of this class: 请参阅此类的文档:
It now providers support for encoding / decoding parameters. 它现在提供对编码/解码参数的支持。
This is pretty simple - you can define your URLSearchParams
and pass them in the second parameter of the http.get
method: 这很简单 - 您可以定义
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 });
When an URL like this http://stackoverflow.com?param1=value 当像http://stackoverflow.com?param1=value这样的网址时
You can get the param1 by code follow: 您可以通过以下代码获取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"];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.