How to ignore properties sent via http

2019-07-25 16:56发布

I have an interface in my application that maintains properties that I want to send to my database, as well as properties that I do not.

Specifically I maintain an property called state that can be set to open or null (closed) which then triggers Angular2's Animation state function. I use this in *ngFor lists to open an close a panel of information about the item.

However, I don't want to store the value of state in my database since it always defaults to null. Currently, I pass the whole object to the http call so the state property gets sent too. How can I instead ignore it?

  pushItemToDay(item: any, dateStr: Date): void {
    let body = JSON.stringify(item);

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    this.http.post(this.baseURL + 'api/addItem/' + dateStr, body, options)
        .toPromise()
        .catch(this.handleError);
  }

1条回答
Rolldiameter
2楼-- · 2019-07-25 17:35

Delete can do damage if the object is used after the post. The function stringify has an additional parameter exactly to ignore unwanted entries.

let source = {
 	'meal': 'burger',
  'milkshake': 'chocolat',
  'extra':'2 hot dogs',
  'free': 'smile'
 };
let ignoreList = [ 'meal', 'extra' ];
 
function replacer(key,value)
{
    if (ignoreList.indexOf(key) > -1) return undefined;
    else return value;
}
 
let data = JSON.stringify(source, replacer);
console.log(data);

查看更多
登录 后发表回答