Multiple Objects into HttpParams

这一生的挚爱 提交于 2019-12-03 08:50:00

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

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.

You can create object containing all parameters and pass this object to fromObject property of HttpParamOptons while creating HttpParams

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

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

this.http.post(URL, body, this.header).subscribe(data => {
 ....
}, error => {
 ....
})
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);
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!