使用angular_2 +

问题描述

我正在尝试使用GET request进行以下angular httpClient的操作,但到目前为止没有成功。任何人都可以帮忙。请求如下。

curl --location --request GET 'MY_URL_TO_SEND' 
--header 'Content-Type: application/json' 
--header 'Authorization: MY_TOKEN' 
--data-raw '{
    "_source": ["title"],"query": {
        "multi_match": {
                "query": "covid","type": "best_fields","fields": ["title.e_ngrams^4","description.e_ngrams","keywords.e_ngrams^2"],"fuzziness": 1
            }
    }
}' 

当我将其粘贴到terminal中时,该命令将起作用,并将返回以下结果。

{
    "took": 1,"timed_out": false,"_shards": {
        "total": 1,"successful": 1,"skipped": 0,"Failed": 0
    },"hits": {
        "total": {
            "value": 6,"relation": "eq"
        },"max_score": 1.0,"hits": [
            {
                "_index": "stats","_type": "_doc","_id": "daily-covid-19-deaths","_score": 1.0,"_source": {
                    "title": "Daily Covid-19 Deaths"
                }
            }]
}
},

但是,当我通过角度进行呼叫时,不仅仅将title返回为_source,还会返回我所有其他参数,这也表明呼叫无法正常工作。

这是我到目前为止尝试过的。

const httpParams: HttpParams = new HttpParams();
httpParams.set('_source',JSON.stringify(['title','slug']));
httpParams.set(
  'query',JSON.stringify({
    multi_match: {
      query: query,type: 'best_fields',fields: [
        'title.e_ngrams^4','description.e_ngrams','keywords.e_ngrams^2',],fuzziness: 1,},})
);

this.http
  .get(environment.ES.searchAPI,{
    headers: this.httpHeaders,params: httpParams,})
  .subscribe((data: any) => {
    this.searchResults.next(this.parseResults(data));
  });

}

这将返回结果给我,但是传递的参数(例如_source)不起作用。它只是返回所有结果。

这是我的角度应用httpClient从上面的代码返回的内容

enter image description here

解决方法

您可以改用POST request

一个例子:

const body = JSON.stringify({
  _source: ['title','slug'],query:{
    multi_match: {
      query: query,type: 'best_fields',fields: [
        'title.e_ngrams^4','description.e_ngrams','keywords.e_ngrams^2',],fuzziness: 1,}
  }
});

const httpHeaders = new HttpHeaders({
    'Content-Type' : 'application/json'
 });

this.httpClient.post(environment.ES.searchAPI,body,{
    headers:httpHeaders
  })    
  .subscribe((data: any) => {
    console.log(data);
  });

那么为什么在您的示例中却得到了所有结果参数?

您的GET request忽略了params: httpParams,因为httpParamsnull

尝试将httpParams.set更改为httpParams = httpParams.set

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...