DonLeo DonLeo - 2 months ago 22
TypeScript Question

Angular2 how to hide empty array in POST

In my filters I have products list. I want to send this array only, when there are some elements. Is it possible?

Request function:

getRecipes(page, pageSize, filters){
let body = JSON.stringify({ "size": pageSize, "page": page, "listOfFilters": filters});
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

return this.http.post('http://localhost:8080/cookbook/recipe/filter',body,options)
.map((res: Response) => res.json());}


Filter Class:

export class Filter{
products = new Array<String>();
rating: {[key: string]:string} = {};
level: {[key: string]:string} = {};
}


Now JSON looks like:

{"size":10,"page":1,"listOfFilters":{"products":[],"rating":{"from":"1","to":"5"},"level":{"from":"1"
,"to":"5"}}}


And I want it to looks like (when products list is empty):

{"size":10,"page":1,"listOfFilters":{"rating":{"from":"1","to":"5"},"level":{"from":"1"
,"to":"5"}}}

Answer

I'm not entirely sure, how you want the endresult to look like, but this is a simple if condition, where you can leverage delete.

if (filters.products.length == 0) {
    delete filters.products;
}

let body = JSON.stringify({ "size": pageSize, "page": page, "listOfFilters": filters });
Comments