Multiple Objects into HttpParams

后端 未结 3 1785
孤街浪徒
孤街浪徒 2021-02-08 07:00

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:



        
3条回答
  •  生来不讨喜
    2021-02-08 07:50

    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.

提交回复
热议问题