# Angular前端应用中HttpParams以json格式进行http多参数传递示例

> 大多数前端应用都需要通过 HTTP 协议与后端服务器通讯。现代浏览器支持使用两种不同的 API 发起 HTTP 请求：XMLHttpRequest 接口和 fetch() API。HttpClient 类基于浏览器提供的 XMLHttpRequest 接口，为 angular 应用程序提供了一个简化的 api 来实现 http 客户端功能；这里记录下项目中实际应用的基础方法使用。

Author: DeathGhost
Published: 2018-09-11 23:25:27
Category: angular
Canonical: https://www.deathghost.cn/article/angular/36
Keywords: angular, angular2 , angular6.x, HttpParams, http请求, HttpClient请求参数, HttpParams参数json形式, json数据, 参数传递, 参数配置

这篇文章只介绍一点，就是angular应用中http多个请求参数操作方法；起初接触angular一直使用HttpParams进行参数设置，结果实际应用中遇到业务判断需要对其作以参数变动。

基础使用大家参考angular官方文档，根模块导入HttpClientModule,然后将HttpClient注入到应用里即可...

假如我们有一个文章列表页面，那么最基本的就是&ldquo;添加文章&rdquo;与&ldquo;编辑文章&rdquo;两个操作，一个接口，我们根据是否有ID判断添加还是编辑，如基础请求结构：

e.g.

_save() {
  const url = `/article/save`;
  const params = new HttpParams()
  .set('title', `${this._formData.title}`)
  .set('content', `${this._formData.title}`);
  this.http.post(url, params).subscribe(
    data => {
      // ...
    },
    error => {
      // ...
    }
  );
}
当然了，我们在写的过程中，肯定只写一个保存方法，在保存时判断添加还是编辑时，那么我们就会这样操作：

<button (click)="update('0')">保存</button>
<button (click)="update('1')">保存</button>
// 0:新增
// 1:编辑
update(t) {
  const params = new HttpParams()
  .set('title', `${this._formData.title}`)
  .set('content', `${this._formData.title}`);
  if (t === '0') {
    // console.log('add');
    params = new HttpParams()
    .set('title', `${this._formData.title}`)
    .set('content', `${this._formData.title}`);
  } else if (t === '1') {
    // console.log('edit');
    params = new HttpParams()
    .set('id', `${this._formData.id}`)
    .set('title', `${this._formData.title}`)
    .set('content', `${this._formData.title}`);
  }
}
_save(params) {
  const url = `/article/save`;
  this.http.post(url, params).subscribe(
    data => {
      // ...
    },
    error => {
      // ...
    }
  );
}
这样，也可以操作，但如果参数过多，或业务逻辑复杂，则不适合了；有没有和jquery那种Ajax一样的，传入一个json对象即可？

当然是有，只是一直没看这里的接口，这里开始，上面的都已经是废话了，就是直接在HttpParams中构造一个json数据进去（HttpParamsOptions）。

![angular前端应用中HttpParams以json格式进行http多参数传递示例](https://www.deathghost.cn/public/upload/article/2018/09/1537006566017.jpg)

angular前端应用中HttpParams以json格式进行http多参数传递示例

let params = {
  id: '',
  title: this.title,
  content: this.content
};

new HttpParams({fromObject: params});
就是这个new HttpParams({fromObject: params})；

这样，我们就可以方便根据业务逻辑判断对其参数作以操作（什么情况添加id，什么情况下删除id）。

## Related

- Previous: [Angular应用中通过socket.io-client搭建实时通信 前端实例安装配置方法](https://www.deathghost.cn/article/angular/35)
- Next: [Angular自定义预加载策略](https://www.deathghost.cn/article/angular/88)
