Angular2如何在POST中隐藏空数组

时间:2016-09-13 07:58:17

标签: angular typescript

在我的过滤器中,我有产品列表。当有一些元素时,我只想发送这个数组。有可能吗?

请求功能:

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

过滤类:

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

现在JSON看起来像:

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

我希望它看起来像(当产品列表为空时):

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

1 个答案:

答案 0 :(得分:0)

我不完全确定,你希望结果如何,但这是一个简单的if条件,你可以利用delete

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

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