Angular 角度4 HttpClient查询参数

Angular 角度4 HttpClient查询参数,angular,typescript,http,lodash,angular-httpclient,Angular,Typescript,Http,Lodash,Angular Httpclient,我一直在寻找一种方法,通过新的HttpClientModule的HttpClient将查询参数传递到API调用中,但尚未找到解决方案。使用旧的Http模块,您可以编写如下内容 getNamespaceLogs(logNamespace){ //设置日志命名空间查询参数 设params=newurlsearchparams(); 参数集('logNamespace',logNamespace); 这个._Http.get(`${API\u URL}/API/v1/data/logs`,{searc

我一直在寻找一种方法,通过新的
HttpClientModule
HttpClient
将查询参数传递到API调用中,但尚未找到解决方案。使用旧的
Http
模块,您可以编写如下内容

getNamespaceLogs(logNamespace){
//设置日志命名空间查询参数
设params=newurlsearchparams();
参数集('logNamespace',logNamespace);
这个._Http.get(`${API\u URL}/API/v1/data/logs`,{search:params})
}
这将导致对以下URL的API调用:

localhost:3001/api/v1/data/logs?logNamespace=somelogsnamespace


但是,新的
HttpClient
get()
方法没有
search
属性,因此我想知道在哪里传递查询参数?

我最终通过
get()
函数上的IntelliSense找到了它。所以,我会把它贴在这里,给任何想找类似信息的人

无论如何,语法几乎相同,但略有不同。需要将参数初始化为
HttpParams()
,而不是使用
URLSearchParams()
,并且
get()
函数中的属性现在被称为
params
,而不是
search

从'@angular/common/http'导入{HttpClient,HttpParams};
getLogs(logNamespace):可以观察到如何分配多个参数

getLogs(参数){
//初始化参数对象
设params=newhttpparams();
//开始分配参数
params=params.append('firstParameter',parameters.valueOne);
params=params.append('secondParameter',parameters.valueTwo);
//使用新参数进行API调用。
返回此值。HttpClient.get(`${API\u URL}/API/v1/data/logs`,{params:params})
具有条件逻辑的多个参数

我经常使用多个参数的另一件事是允许使用多个参数,而无需在每次调用中都显示这些参数。使用Lodash,从API调用中有条件地添加/删除参数非常简单。Lodash、下划线或vanilla JS中使用的确切函数可能因应用程序而异,但我不知道我发现检查属性定义效果很好。下面的函数将只传递在传递到函数中的parameters变量中具有相应属性的参数

getLogs(参数){
//初始化参数对象
设params=newhttpparams();
//开始分配参数
如果(!\未定义(参数)){
params=..isUndefined(parameters.valueOne)?params:params.append('firstParameter',parameters.valueOne);
params=\未定义(parameters.valueTwo)?params:params.append('secondParameter',parameters.valueTwo);
}
//使用新参数进行API调用。
返回此值。HttpClient.get(`${API\u URL}/API/v1/data/logs`,{params:params})
乔什拉特克是对的

在angular.io中,不推荐使用@angular/http中的URLSearchParams。相反,您应该使用@angular/common/http中的HttpParams。代码与joshrathke编写的代码非常相似。 对于保存在对象中的多个参数,例如

{
  firstParam: value1,
  secondParam, value2
}
你也可以这样做

for(let property in objectStoresParams) {
  if(objectStoresParams.hasOwnProperty(property) {
    params = params.append(property, objectStoresParams[property]);
  }
}
如果您需要继承的属性,那么相应地删除hasown属性。

您可以(在版本5+中)在创建HttpParameters时使用fromObjectfromString构造函数参数,使事情变得更简单

    const params = new HttpParams({
      fromObject: {
        param1: 'value1',
        param2: 'value2',
      }
    });

    // http://localhost:3000/test?param1=value1&param2=value2
或:


RequestOptions类中URLSearchParams类型的search属性在angular 4中被弃用。相反,您应该使用params类型的URLSearchParams

属性作为更简洁的解决方案:

this._Http.get(`${API_URL}/api/v1/data/logs`, { 
    params: {
      logNamespace: logNamespace
    } 
 })

你可以这样通过

let param: any = {'userId': 2};
this.http.get(`${ApiUrl}`, {params: param})

如果您有一个可以转换为
{key:'stringValue'}
对的对象,则可以使用此快捷方式将其转换为:

this._Http.get(myUrlString, {params: {...myParamsObject}});
我只是喜欢扩展语法!

和Angular 7, 我通过使用以下命令而不使用HttpParams使其正常工作

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

export class ApiClass {

  constructor(private httpClient: HttpClient) {
    // use it like this in other services / components etc.
    this.getDataFromServer().
      then(res => {
        console.log('res: ', res);
      });
  }

  getDataFromServer() {
    const params = {
      param1: value1,
      param2: value2
    }
    const url = 'https://api.example.com/list'

    // { params: params } is the same as { params } 
    // look for es6 object literal to read more
    return this.httpClient.get(url, { params }).toPromise();
  }
}

第一个代码段是错误的。
let params=new-HttpParams();params.set(…)
将无法按预期工作。请参阅@joshrathke您可以添加如何将头和参数添加在一起吗?@SavadKP您可以这样设置它们。http.get(url,{headers:headers,params:params});并阅读有关新的HttpHeader,如HttpParamsI guess
新的HttpParams({fromObject:{param1:'value1',…});
是最简单的方法(angular 5+),然后是
params.set(…)
。这不再需要了。您可以直接将JSON对象传递给HttpClient。
const params={'key':'value}
到:
http.get('/get/url',{params:params})
@danger89 True。但请注意:只允许使用string或string[]值!节省了大量时间。我通过将查询参数作为字符串附加到请求url来构造url。使用Angular 7,您可以将参数作为对象编写并像这样使用:
this.httpClient.get(url,{params}
检查True,但这会导致键入window@DanLatimer您不必使用任何,因此可以一直使用键入,直到将其传递给
params
import { HttpClient } from '@angular/common/http';

export class ApiClass {

  constructor(private httpClient: HttpClient) {
    // use it like this in other services / components etc.
    this.getDataFromServer().
      then(res => {
        console.log('res: ', res);
      });
  }

  getDataFromServer() {
    const params = {
      param1: value1,
      param2: value2
    }
    const url = 'https://api.example.com/list'

    // { params: params } is the same as { params } 
    // look for es6 object literal to read more
    return this.httpClient.get(url, { params }).toPromise();
  }
}