【问题标题】:Input fields to json object post requestjson对象发布请求的输入字段
【发布时间】:2018-06-15 02:53:57
【问题描述】:

所以我有一些可选的输入字段,我需要构建一个 json 对象,然后将其发送到 http.post。可选意味着如果字段为空,那么我也不会将其添加到 json 属性中。这是以下输入字段。

<input type="text" [(ngModel)]="searchQuery" placeholder="Keyword">

     <div class="row">
        <div class="col-lg-6">
            <p-calendar id="kera" [(ngModel)]="startDate" dateFormat="yy-mm-dd" placeholder="Start date" [showIcon]="true"></p-calendar>
        </div>
        <div class="col-lg-6">
            <p-calendar id="kera" [(ngModel)]="endDate" dateFormat="yy-mm-dd" placeholder="End date" [showIcon]="true"></p-calendar>
        </div>
    </div>

将发送到 http 的预期对象应如下所示:

  "search": {
    "scope": [2, 3, 32],
    "type": "basic",
    "text": {
      "value": searchQuery, //string variable coming from UI

    },

    "date": {
      "type": "range",
      "from": startDate, //string variable coming from UI
      "to": endDate //string variable coming from UI
    }
  }

是否应该使用 json.prase 来完成?或者应该是类似这样的东西,

 var search = {};
 search.text = { value: "", fields: [] };
 {value: "", fields: Array(0)}
 seach.text.value = "tom";
 search.text.value = "tom";
 search.text.fields.push("subject");
 search.text.fields.push("body"); 

所以我必须在发送之前手动构建对象

【问题讨论】:

  • 您不必将其解析为 json 只需将其作为对象发送
  • 但是我必须在发送之前手动构建它,如果字段为空我不发送属性,不知道如何实现这个

标签: javascript json angular rest api


【解决方案1】:

这取决于您发送给它的系统。如果您发送一个空对象并且该 API 中没有任何验证,那么该 API 将被调用并且它会更正。而关于形成对象只需将其形成为 js

let data = { 
     /// create the structure here not as you do 
     'search':{ 
         'text':"blabla",  
         ... 
     },
     .... 
}
this.http.post(url, data);

【讨论】:

  • 这个问题我不能这样形成,因为 api 将来可能会改变
【解决方案2】:

我会使用一个表单,你会得到一个带有属性和值的漂亮对象。然后也使用辅助对象,检查表单对象,如果属性有值,然后将具有相应值的属性插入到辅助对象中,最后发送到后端。

您可以使用反应式表单或模板驱动表单。我自己喜欢使用响应式表单,因为它具有一些不错的功能,并且您可以更好地控制表单。此外,由于您使用的是数组,因此模板驱动的表单确实不支持。因此,以下是为您提供的反应形式示例:

myForm: FormGroup;

constructor(private fb: FormBuilder) {
    this.myForm = fb.group({
      field1: [''],
      field2: ['']
    })
}

模板:

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
  <input formControlName="field1">
  <input formControlName="field2">
  <button type="submit">Submit</button>
</form>

因此,在这种情况下,在您提交时,您会得到如下对象:

{
  "field1": "",
  "field2": ""
}

在您的提交方法中迭代对象属性,如果该属性对您的帮助对象有值,则设置属性和值:

onSubmit(values) {
  let obj = {};
  for(let prop in values) {
    // do not try to trim unless type is 'string'
    if((typeof values[prop] == 'string')) {
      values[prop] = values[prop].trim();
    }
    // property has value, insert property and value to helper obj
    if(values[prop].length) {
      obj[prop] = values[prop];
    }
  }
  // post this object to your backend
  console.log(obj)
}

这是一个带有上述代码的 StackBlitz :)

由于您还涉及数组,因此您需要研究反应形式以及如何在该反应形式中使用 FormArrayhttps://angular.io/guide/reactive-forms

【讨论】:

    【解决方案3】:

    好的,一个优雅的解决方案是手动创建一个对象:

    var searchObj = { 
      "search": {
      "scope": [2, 3, 32],
      "type": "basic",
      "date": {
        "type": "range",
        "from": "", 
        "to" : "" 
      },
      "text": {
      value: "", fields: [],
      },
      "HasAttachmentsOnly": hasAttachments,
    
    }
    };
    
    
    searchObj.search.text.value = searchQuery;
    searchObj.search.date.from = startNumber;
    searchObj.search.date.to = endNumber; 
    
    
    if (body){
    searchObj.search.text.fields.push("body");
    }
    if (subject){
      searchObj.search.text.fields.push("subject");
      }
      if (attachName){
        searchObj.search.text.fields.push("attachmentname");
        }
        if (attachCont){
          searchObj.search.text.fields.push("attachmentcontent");
          }
    
    
    
      return this.http.post('/api/search/', 
      searchObj
     ).map(data => data)
    
        }
    
      }
    

    【讨论】:

      猜你喜欢
      • 2014-12-08
      • 2018-10-24
      • 2013-10-25
      • 2019-04-19
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 2014-03-21
      • 1970-01-01
      相关资源
      最近更新 更多