当前位置:  开发笔记 > 编程语言 > 正文

如何将URL参数(查询字符串)传递给Angular上的HTTP请求?

如何解决《如何将URL参数(查询字符串)传递给Angular上的HTTP请求?》经验,为你挑选了6个好方法。

大家好我在Angular上创建HTTP请求,但我不知道如何添加url参数(查询字符串).

this.http.get(StaticSettings.BASE_URL).subscribe(
  (response) => this.onGetForecastResult(response.json()),
  (error) => this.onGetForecastError(error.json()),
  () => this.onGetForecastComplete()
);

现在我的StaticSettings.BASE_URL就像一个没有查询字符串的网址,如:http://atsomeplace.com/ 但我希望它是http://atsomeplace.com/?var1=val1&var2=val2

哪个var1和var2适合我的Http请求对象?我想像对象一样添加它们.

{
  query: {
    var1: val1,
    var2: val2
  }
}

然后只是Http模块完成工作将其解析为URL查询字符串.



1> toskv..:

HttpClient的方法允许您设置PARAMS在它的选项.

您可以通过从@ angular/common/http包导入HttpClientModule来配置它.

import {HttpClientModule} from '@angular/common/http';

@NgModule({
  imports: [ BrowserModule, HttpClientModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

之后,您可以注入HttpClient并使用它来执行请求.

import {HttpClient} from '@angular/common/http'

@Component({
  selector: 'my-app',
  template: `
    

Hello {{name}}

`, }) export class App { name:string; constructor(private httpClient: HttpClient) { this.httpClient.get('/url', { params: { appid: 'id1234', cnt: '5' }, observe: 'response' }) .toPromise() .then(response => { console.log(response); }) .catch(console.log); } }

对于版本4之前的角度版本,您可以使用Http服务执行相同的操作.

Http.get方法需要实现一个目的RequestOptionsArgs作为第二参数.

该对象的搜索字段可用于设置字符串或URLSearchParams对象.

一个例子:

 // Parameters obj-
 let params: URLSearchParams = new URLSearchParams();
 params.set('appid', StaticSettings.API_KEY);
 params.set('cnt', days.toString());

 //Http request-
 return this.http.get(StaticSettings.BASE_URL, {
   search: params
 }).subscribe(
   (response) => this.onGetForecastResult(response.json()), 
   (error) => this.onGetForecastError(error.json()), 
   () => this.onGetForecastComplete()
 );

Http类的文档有更多细节.它可以发现这里和工作的例子在这里.


这对我有用:`http.get(url,{params:{var1:val1,var2:val2}})`
`search`属性已从4.0.0中删除 - >使用`params`代替
一个要点:https://gist.github.com/MiguelLattuada/bb502d84854ad9fc26e0如何使用URLSearchParams对象,再次感谢@toskv
@SukumarMS真的不需要任何特别的东西,因为它是路径的一部分.只需连接字符串'blabla.com/page/'+ page +'/ activeFilter'+ activeFilter.或者如果你想使用模板文字\`blabla.com/page/$ {page}/$ {activeFilter} \`.

2> Radouane ROU..:

编辑角度> = 4.3.x.

HttpClient已与HttpParams一起推出.下面是一个使用示例:

import { HttpParams, HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

let params = new HttpParams();
params = params.append('var1', val1);
params = params.append('var2', val2);

this.http.get(StaticSettings.BASE_URL, {params: params}).subscribe(...);

(老答案)

编辑角度> = 4.x

requestOptions.search已被弃用.requestOptions.params改为使用:

let requestOptions = new RequestOptions();
requestOptions.params = params;

原始答案(Angular 2)

您需要导入URLSearchParams如下

import { Http, RequestOptions, URLSearchParams } from '@angular/http';

然后构建您的参数并按如下方式生成http请求:

let params: URLSearchParams = new URLSearchParams();
params.set('var1', val1);
params.set('var2', val2);

let requestOptions = new RequestOptions();
requestOptions.search = params;

this.http.get(StaticSettings.BASE_URL, requestOptions)
    .toPromise()
    .then(response => response.json())
...


不适合我.我深入研究了源代码,发现http.get的第二个参数需要一个RequestOptionsArgs接口,而URLSearchParams没有实现.将RequestParams包装在RequestOptions对象中是有效的.虽然有快捷方式会很高兴.
你是完全正确的,我忘记了`RequestOptions`.我更新了我的答案.

3> Rahmathullah..:

版本5+

使用Angular 5及更高版本,您不必使用HttpParams.您可以直接发送您的json对象,如下所示.

let data = {limit: "2"};
this.httpClient.get(apiUrl, {params: data});

请注意,数据值应为字符串,即; { params: {limit: "2"}}

版本4.3.x +

使用来自@ angular/common/http的HttpParams,HttpClient

import { HttpParams, HttpClient } from '@angular/common/http';
...
constructor(private httpClient: HttpClient) { ... }
...
let params = new HttpParams();
params = params.append("page", 1);
....
this.httpClient.get(apiUrl, {params: params});

可能会帮助一些!



4> 小智..:

Angular 6

您可以使用params传入get调用所需的参数:

this.httpClient.get(url, { params: x });

其中x = {property:"123"}.

至于记录"123"的api函数:

router.get('/example', (req, res) => {
    console.log(req.query.property);
})


这是在版本5中添加的更改。已在此处添加/sf/ask/17360801/

5> ethemsulan..:

我的例子

private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});

我的方法

  getUserByName(name: string): Observable {
    //set request params
    let params: URLSearchParams = new URLSearchParams();
    params.set("name", name);
    //params.set("surname", surname); for more params
    this.options.search = params;

    let url = "http://localhost:8080/test/user/";
    console.log("url: ", url);

    return this.http.get(url, this.options)
      .map((resp: Response) => resp.json() as MyObject[])
      .catch(this.handleError);
  }

  private handleError(err) {
    console.log(err);
    return Observable.throw(err || 'Server error');
  }

在我的组件中

  userList: User[] = [];
  this.userService.getUserByName(this.userName).subscribe(users => {
      this.userList = users;
    });

邮差

http://localhost:8080/test/user/?name=Ethem



6> mjwrazor..:

如果您打算发送多个参数.

零件

private options = {
  sort:   '-id',
  select: null,
  limit:  1000,
  skip:   0,
  from:   null,
  to:     null
};

constructor(private service: Service) { }

ngOnInit() {
  this.service.getAllItems(this.options)
    .subscribe((item: Item[]) => {
      this.item = item;
    });
}

服务

private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});
constructor(private http: Http) { }

getAllItems(query: any) {
  let params: URLSearchParams = new URLSearchParams();
  for(let key in query){
    params.set(key.toString(), query[key]);
  }
  this.options.search = params;
  this.header = this.headers();

并继续你的http请求@ethemsulan如何做.

服务器端路由

router.get('/api/items', (req, res) => {
  let q = {};
  let skip = req.query.skip;
  let limit = req.query.limit;
  let sort  = req.query.sort;
  q.from = req.query.from;
  q.to = req.query.to;

  Items.find(q)
    .skip(skip)
    .limit(limit)
    .sort(sort)
    .exec((err, items) => {
      if(err) {
        return res.status(500).json({
          title: "An error occurred",
          error: err
        });
      }
      res.status(200).json({
        message: "Success",
        obj:  items
      });
    });
});

推荐阅读
php
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有