16

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

[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:

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

1
  • little not clear about your q?.. If you want to send it as objects you can set using angular common HttpClient or http but not as params Commented Oct 16, 2017 at 5:56

3 Answers 3

34

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The fact that we need to use an append method instead of a set method was surprising to me. Add to this, that we also need to reassign the object to itself was even more so.
@Stephane I agree that it's confusing at first glance. I updated my answer with a little more detail.
@RichMcCluskey sorry for asking a question in comment box because i am ban to ask question on this plateform. my problem is related to this answer so please take a look here stackblitz.com/edit/angular-66qunm
15

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 => {
 ....
})

1 Comment

your answer has saved me tons of codding.
1

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

1 Comment

The problem is that I am sending like this "...categoryId=[1,2]", but on api side I need to get like this "...categoryId=1&categoryId=2..." How can I do that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.