角度> = 4.3,httpClient.get参数为空 [英] Angular >= 4.3, httpClient.get params empty

查看:86
本文介绍了角度> = 4.3,httpClient.get参数为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的Http请求迁移到HttpClient请求. 我能够迁移post查询,但是在迁移get查询时遇到问题.这样做时,后端没有分别接收任何参数,它告诉我该参数未提供且为空.

I'm trying to migrate my Http requests to HttpClient requests. I was able to migrate my post queries but I'm facing a problem while migrating get queries. When I do so, my backend doesn't receive any parameters respectively, it tells me that the parameters are not provided and empty.

我做错了吗?

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

constructor(private httpClient: HttpClient) {}

findItems() {
   let params: HttpParams = new HttpParams();
   params.set('something', 'hello');

   this.httpClient.get<any[]>('http://localhost:3000/apath/', {params})
    .subscribe((results: any[]) => {
      console.log(results);
    }, (errorResponse: any) => {
       console.error(errorResponse);
    });
}

有什么主意吗?

推荐答案

当前HttpParams是不可变的,您应该将参数设置如下:

Currently HttpParams is immutable, you should set params as below:

// for set method
let params: HttpParams = new HttpParams().set('something', 'hello');
// for append method
let params: HttpParams = new HttpParams().append('something', 'hello');


HttpParams setappend方法将用setappend用新更新的实例覆盖原始的params实例,最后返回新实例.


HttpParams's set and append method will overwrite the original params instance with the newly updated one by set and append, and finally return the new instance.

因此,我们可以按以下几行内容进行操作:

So we can do it in multiple lines as below:

let params: HttpParams = new HttpParams();
params = params.set('something', 'hello');          
params = params.append('something2', 'hello2');

柱塞演示

Plunker demo

重要提示:

自Angular v5.0.0起,您可以使用HttpParamOptions中的fromObject来同时添加多个参数.

Since Angular v5.0.0, you can use fromObject from HttpParamOptions to add multiple parameters at the same time.

const param = new HttpParams({fromObject: {aaa: '1', bbb: '222'}});

您还可以直接将object参数设置为HttpClient方法

Also you can set object parameters to HttpClient methods directly

const obj = {aaa: '1', bbb: '222'};
this.http.get('test', { params: obj}).subscribe();

请参考演示,以获取第二种方式,请检查浏览器的网络以确认参数已成功添加.

Refer demo, for the second way, please check browser's network to confirm the parameters has been added successfully.

这篇关于角度&gt; = 4.3,httpClient.get参数为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆