如何忽略通过http发送的属性 [英] How to ignore properties sent via http

查看:117
本文介绍了如何忽略通过http发送的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个界面,用于维护我要发送到我的数据库的属性,以及我不会发送的属性。

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.

具体来说,我维护一个名为的属性,可以设置为打开 null (关闭)然后触发Angular2的动画功能。我在 * ngFor 列表中使用它来打开关闭该项目的信息面板。

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.

但是,我不希望在我的数据库中存储state的值,因为它总是默认为 null 。目前,我将整个对象传递给http调用,因此也会发送 state 属性。我怎么能忽略它呢?

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


推荐答案

删除可能会造成损害在帖子之后使用对象。函数stringify有一个额外的参数,完全忽略不需要的条目。

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

这篇关于如何忽略通过http发送的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆