Angular Http 客户端 - 如何将嵌套参数对象传递给 GET API [英] Angular Http Client - How to Pass Nested Params Object to GET API

查看:47
本文介绍了Angular Http 客户端 - 如何将嵌套参数对象传递给 GET API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是最新版本的 angular (8).我正在将我的 Http 请求从原始 http 转换为新的 http 客户端.我正在调用 GET API,在其中我以以下方式发送嵌套参数:

I am using latest version of angular (8). I am doing a conversion of my Http request from the original http to the new http client. I am calling a GET API where I am sending a nested params in the following way:

let data: any = {filters: {"4e9bc554-db54-4413-a718-b89ffdb91c2f": "465c1ab-2b89-4b51-8a7b-5d2ac862ee32"}, is_indexed: true}
return this.httpClient.get<Register[]>('/registers/', {headers: headers, params: data});

上面的代码,嵌套的参数没有被识别.如何使用 HttpClient 作为嵌套参数正确传递?Ps 在旧的 Http 中,使用上面的代码是没有问题的.提前感谢您的帮助.

The above code, the nested params are not recognised. How do I properly pass as nested params using the HttpClient? Ps In the old Http, there was no issue using the above code. Thanks for the help in advance.

更新网址将类似于以下内容:

UPDATE Url would look similar to this:

https://www.somepapi.com/registers/?filters=%7B%224e9bc554-db54-4413-a718-b89ffdb91c2f%22:%228465b5c14b2-8a7b-5d2ac862ee32%22%7D&is_indexed=true;

推荐答案

您可以递归地遍历数据对象以将其展平.

You could recursively iterate through the data object to flatten it out.

getData(data: any) {
  let params = {};    

  this.buildHttpParams(params, data, "");

  return this.httpClient.get("...", {params: params})
}

private buildHttpParams(params: any, data: any, currentPath: string) {
    Object.keys(data).forEach(key => {
        if (data[key] instanceof Object) {
            this.buildHttpParams(params, data[key], `${currentPath}${key}.`);
        } else {
            params[`${currentPath}${key}`] = data[key];
        }
    });
}

这将改变我们的数据对象:

This will change our data object from:

{
  filters: {
    "4e9bc554-db54-4413-a718-b89ffdb91c2f": "465c1ab-2b89-4b51-8a7b-5d2ac862ee32"
  },
  "is_indexed": true
}

到:

{
  "filters.4e9bc554-db54-4413-a718-b89ffdb91c2f": "465c1ab-2b89-4b51-8a7b-5d2ac862ee32",
  "is_indexed": true
}

这篇关于Angular Http 客户端 - 如何将嵌套参数对象传递给 GET API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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