1 使用表單獲取到數據之後,是對象類型的數據以下圖javascript
然後臺須要返回的數據是這種key:value的形式傳入html
2 廢話很少說直接上代碼(代碼只截取部分,僅供參考跑不起來,最後又一個小demo能夠運行)java
public discountArr = []; // 折扣數組容器 public discountContent = { 'name': '', 'value': '' }; // 折扣轉換對象容器 public setDiscount = {}; // 折扣返回數據 ngOnInit() { // 頁面初始化發送請求獲取數據折後 this.service.getProductDiscount(this.userId).subscribe(data => { if (data.code !== 0) { // TODO 錯誤處理 console.log(data.message); } else { 返回成功後把獲取到的數據賦值給頁面的數據 console.log(data, '折扣'); this._discount.EIP = data.result.EIP; this._discount.EBS = data.result.EBS; this._discount.ECS = data.result.ECS; this._discount.SLB = data.result.SLB; this._discount.OSS = data.result.OSS; this._discount.CPS = data.result.CPS; this._discount.CAAS = data.result.CAAS; this._discount.VPC = data.result.VPC; this._discount.SBW = data.result.SBW; this._discount.RDSMysql = data.result.RDSMysql; this._discount.CDN = data.result.CDN; } }); // 表單獲取到的數據 this.discount = this.fb.group({ EIP: [10, [Validators.required]], EBS: [9, [Validators.required]], ECS: [null, [Validators.required]], SLB: [null, [Validators.required]], OSS: [null, [Validators.required]], CPS: [null, [Validators.required]], CAAS: [null, [Validators.required]], VPC: [null, [Validators.required]], SBW: [null, [Validators.required]], RDSMysql: [null, [Validators.required]], CDN: [null, [Validators.required]], }); console.log(this.discount.value); } // 表單提交執行函數 onSubmit() { // tslint:disable-next-line:forin // 循環表單獲取的數據 for (const key in this.discount.value) { // 每次執行行前讓新對象爲空 this.discountContent = { 'name': '', 'value': '' }; // 若是爲空的話 if (!this.discountContent[key]) { // 把拆分開的數據分別放入key value this.discountContent.name = key; this.discountContent.value = this.discount.value[key]; } // 每次拆分紅功插入數組 this.discountArr.push(this.discountContent); } // 轉換成後臺須要的數據格式 this.setDiscount = { operatorId: this.marketId, discount: this.discountArr, }; console.log(this.setDiscount); // 發送修改記錄 this.service.changeProductDiscount(this.userId, this.setDiscount).subscribe(data => { if (data.code != 0) { // TODO 錯誤處理 this.notification.create(`error`, '失敗', data.message); } else { this.notification.create(`success`, '成功', '折扣已修改爲功'); } }); }
3 數據轉換 demo 示例 (這個能夠跑)sql
<!DOCTYPE html> <html> <head> <title></title> </head> <body> </body> <script type="text/javascript"> var json = { "CAAS":10, "CDN": 10, "CPS": 10, "EBS": 10, "ECS": 10, "EIP": 10, "OSS": 10, "RDSMysql": 10, "SBW": 10, "SLB": 10, "VPC": 10 }; var arr = []; var json1= {}; for(let key in json){ json1 = {}; if(!json1[key]){ json1.name = key; json1.value = json[key]; } arr.push(json1); } console.log(arr); </script> </html>