typescript 将多个对象放入 HttpParams

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46761973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:58:30  来源:igfitidea点击:

Multiple Objects into HttpParams

angulartypescriptangular-httpclient

提问by Juanker

I have some categories in a formcontrol, I send them in an array of string like this:

我在表单控件中有一些类别,我将它们以这样的字符串数组发送:

[1,4,6]

[1,4,6]

And that is my actual code:

这是我的实际代码:

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
}

But I want to send them as an array of objects, with the old version of angular Http I was able to do a foreach of the object and append every category. But I don't know how to get every category and make each one an append to params. I need to get like this:

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

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

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

回答by Rich McCluskey

You can use .appendto append values to a parameter and give you the result you are looking for when dealing with an array of values. .setis used to set or replace a value for a parameter. So really you should be doing something more like the following:

您可以使用.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
};


It's not obvious, but the .appendmethod does not mutate the HttpParamsobject it was called from but instead returns a new object. This is why we reassign httpParamsin the example above. Also, .appendcan be called without first using .setto set the parameter.

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

回答by Altaf Shaikh

You can create object containing all parameters and pass this object to fromObjectproperty of HttpParamOptonswhile creating HttpParams

您可以创建包含所有参数的对象并将此对象传递给创建时的fromObject属性HttpParamOptonsHttpParams

let data={
   firstname:'xyz',
   lastname:'pqr'
}

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

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

回答by AddWeb Solution Pvt Ltd

May be this is what you are looking for

可能这就是你要找的

component file:

组件文件:

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);
  }
}