简体   繁体   English

JSON对象发布请求的输入字段

[英]Input fields to json object post request

So I have some input fields which are optional and I require to build a json object which will be sent then to http.post. 所以我有一些输入字段是可选的,我需要构建一个json对象,然后将其发送到http.post。 Optional means if fields are empty then I don't add it to a json, property too. 可选的意思是,如果字段为空,那么我也不会将其添加到json属性中。 Here is the following input fields. 这是以下输入字段。

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

The expecting object that will be sent to http should look like this: 将发送到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
    }
  }

Should it be done using json.prase? 应该使用json.prase完成吗? Or should be something similar like this, 或者应该是类似的东西,

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

So I have to manually build object before sending it 所以我必须在发送对象之前手动构建对象

it depends on the system that you send to it . 这取决于您发送给它的系统。 and if you send an empty object and there is no any validation in that API then the API will called and it will correct . 如果发送的对象为空,并且该API中没有任何验证,则该API将被调用并且将更正。 and about forming the object just form it as a js 关于形成对象只是将其形成为js

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

I would use a form, you get a nice object with properties and values. 我会使用一种表格,您会得到一个带有属性和值的漂亮对象。 Then also use a helper object, check the form object, if the properties have values, then insert those properties with corresponding values into the helper object, which you in the end send to your backend. 然后还使用一个辅助对象,检查表单对象,如果属性具有值,然后将具有相应值的那些属性插入到辅助对象中,最终将其发送到后端。

You can use a reactive form or a template driven form. 您可以使用反应形式或模板驱动形式。 I like to use reactive form myself as it has some nice features and you have better control over your form. 我喜欢自己使用反应式表单,因为它具有一些不错的功能,并且您可以更好地控制表单。 Also since you are using array(s), template driven forms really do not have support for that. 另外,由于您使用的是数组,因此模板驱动的表单实际上不支持该数组。 So below is a sample for you of reactive forms: 因此,以下是为您提供反应式的示例:

myForm: FormGroup;

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

Template: 模板:

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

So on your submit in this case, you get an object like: 因此,在这种情况下,在提交时,您将得到一个对象,例如:

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

Iterate the object properties in your submit method, set property and value if the property has a value to your helper object: 迭代您的Submit方法中的对象属性,如果该属性对您的辅助对象具有值,则设置属性和值:

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

Here's a StackBlitz with above code :) 这是上面代码的StackBlitz :)

Since you also have array(s) involved, you would want to look into reactive forms and how to use FormArray in that reactive form: https://angular.io/guide/reactive-forms 由于还涉及到数组,因此您需要研究反应形式以及如何以该反应形式使用FormArrayhttps : FormArray

Ok so an elegant solution was to create an object manually: 好吧,一个好的解决方案是手动创建一个对象:

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)

    }

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM