本文介绍了多个对象到HttpParams中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在formcontrol中有一些类别,我将它们发送到这样的字符串数组中:

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

那是我的实际代码:

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并附加每个类别.但是我不知道如何获取每个类别并将每个类别添加为params的附加项.我需要这样:

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:

推荐答案

您可以使用.append将值附加到参数中,并为您提供在处理值数组时要查找的结果. .set用于设置或替换参数值.因此,实际上您应该做一些类似以下的事情:

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

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对象发生突变,而是返回一个新对象.这就是为什么我们在上面的示例中重新分配httpParams的原因.另外,无需先使用.set设置参数即可调用.append.


It's not obvious, but the .append method does not mutate the HttpParams object it was called from but instead returns a new object. This is why we reassign httpParams in the example above. Also, .append can be called without first using .set to set the parameter.

这篇关于多个对象到HttpParams中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:44