多个对象到 HttpParams

Multiple Objects into HttpParams

我在表单控件中有一些类别,我将它们发送到一个字符串数组中,如下所示:

[1,4,6]

这是我的实际代码:

let categoryIds = new Array<String>()
this.selectedCategories.forEach((value: string, key: string) =>
  categoryIds.push(key))

let requestOptions = {
    params: new HttpParams()
        .set('title', this.createNewForm.controls['title'].value)
        .append('content', this.createNewForm.controls['content'].value)
        .append('categoryids', categoryIds.toString()),              
    withCredentials: true
}

但我想将它们作为对象数组发送,使用旧版本 angular Http 我能够对对象执行 foreach 并附加每个类别。 但我不知道如何获取每个类别并使每个类别成为参数的附加项。 我需要这样:

...categoryId=1&categoryId=4&categoryId=6...

可能这就是您要找的东西

组件文件:

import { Component } from '@angular/core';
import { HttpParams } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

data = [
       {id:'_', title:'_', content:'_'},
       ....,
       ....
       ];

mainArr:any = [];

constructor(){}

getCategory(item){
    this.mainArr.push({title:item.title,content:item.content,categoryId:item.id});

   console.log('mainArr',this.mainArr);

   let requestOptions = {
        params: new HttpParams()
        .append('data', this.mainArr),
        withCredentials: true
    }

   console.log('requestOptions',requestOptions);
  }
}

您可以使用 .append 将值附加到参数,并在处理值数组时为您提供所需的结果。 .set 用于设置或替换参数的值。所以你真的应该做更像下面的事情:

let httpParams = new HttpParams()
  .set('title', this.createNewForm.controls['title'].value)
  .set('content', this.createNewForm.controls['content'].value);

categoryIds.forEach(id => {
  httpParams = httpParams.append('categoryId', id);
});

const requestOptions = {
  params: httpParams,
  withCredentials: true
};

这并不明显,但是 .append 方法不会改变调用它的 HttpParams 对象,而是 returns 一个新对象。这就是我们在上面的示例中重新分配 httpParams 的原因。此外,可以调用 .append 而无需先使用 .set 设置参数。

您可以创建包含所有参数的对象,并在创建 HttpParams

时将此对象传递给 HttpParamOptonsfromObject 属性
let data={
   firstname:'xyz',
   lastname:'pqr'
}

let body=new HttpParams({fromObject:data})

this.http.post(URL, body, this.header).subscribe(data => {
 ....
}, error => {
 ....
})