HTTP POST - Json

时间:2017-05-10 23:09:46

标签: angular

我试图以嵌套格式发布我的json值,但是在我的代码中,我的数据是单独提交的,这是数据库中的约束。我从手机应用程序中选择了一些医生,当我点击保存时,httpRequest会提交所有单独选择的医生,如嵌套格式。如何以嵌套格式提交数据?

我的代码

Hospitals = {
  hospital : "New York hospital",
  doctor: {
     details: {  
      id: "",
      ward: ""          
     }
  }
}

//this is how i post to the server 
 saveDoctorsForHospitals(){   
    Object.keys(this.Doctors).filter(key => this.Doctors[key].find)
       .forEach(key => {
           this.Hospitals.Doctors.details.id = this.Docotrs[key].id
           this.Hospitals.Doctors.details.ward = this.Doctors[key].ward

    this.httpService.submitAll(this.Hospitals)
        .subscribe(data => {
           console.log(data);   
        })

这就是我现在提交数据的方式

  object 1         
    "hospital" : "McJames",
    "Doctor" : {
       "1" : {
          "id": 1269,
          "ward": "Demarco",                    
       }        
  Object 2
     "hospital" : "McJames",
     "Doctor" : {
        "2" : {
           "id": 1269,
           "ward": "Demarco",     
        }


//but i want to be this 

    {
      "hospital" : "McJames",
      "Doctor" : {
         "1" : {
           "id": 1269,
            "ward": "Demarco",    
         },

         "2" : {
            "id": 1275,
            "ward": "Eden",
          }
        }
      }

已更新 - 数据包装

Hospitals = {
  hospital : "New York hospital",
  doctor: [{
     details: {  
      id: "",
      ward: ""          
     }
  }]
}

1 个答案:

答案 0 :(得分:1)

这里的代码:

Hospitals = {
  hospital : "New York hospital",
  doctor: {
     details: {  
      id: "",
      ward: ""          
     }
  }
}

定义您要发布的内容。这个数据结构说你有一个带有字符串值的医院属性和一个作为对象的医生属性。如果您需要多位医生,您需要更改此结构,以便将医生定义为阵列。

您可以使用以下界面:

interface Hospital {
    hospital: string;
    doctors: Doctors[]
}
interface Doctors {
    id: number,
    ward: string
}

class Test {
    hospitals: Hospital[] = [];
    constructor() {
        this.hospitals.push({
            hospital: "New York Hospital",
            doctors: [{
                id: 1269,
                ward: "test"
            }]
        })
    }
    data() {
        return JSON.stringify(this.hospitals);
    }
}