Before doing a crud method on a page, in reality the Webapi module is often written in separate service, so modify the original design and structure, or need a lot of knowledge.
2017.11.15 Add patch method to improve service program optimization notation
2017.11.27 added promise return value processing, the server returns the error message after processing.
Because all of the crud methods are written in the service, the code in the background is much simpler, and the callback needs more information, in short, it can run normally:
1 Import {Component, OnInit} from ' @angular/core '; 2 Import {Patient, patientservice} from './patients.service '; 3 4 @Component ({5 selector: ' Patient-component ', 6 templateurl: ' App/app-patient/patient.component.html ', 7 Providers: [Patientservice] 8}) 9 Export class Patientcomponent implements OnInit {results:string[];11 Mypati entlist:patient[] = [];12 mypatient:patient = null;13 Constructor (private Mypatientservice:patientservice) 14 {}15 ngoninit (): void {this.results = ["Ngoninit () method"];17 This.getall ();}19 getall () {This.myPatientService.getall (). Then (data = This.mypatientlist = data);}22 getbyId (id:string ) {this.myPatientService.getbyId (ID). Then (data = This.mypatient = data);}26 Httppostexample (F Irstname:string, lastname:string) {this.mypatient = new Patient ({id: ', firstname:firstname, Lastname:las Tname, MiddleName: ", BirthDate: ', EmailAddress: ', ZIPCODE: ', Citizenservicenumber: ', City: ', Gender: '} '; 29//Use the then method to wait for the return result, Process business requirements. Then rather into a callback function. This.myPatientService.httpPostExample (This.mypatient) Then (_ = This.getall ());}32 Httpputexample (Id:string, firstname:string, lastname:string) {this.mypatient = new Patient ({id: ', firstname:firstname, Lastname:lastname, MiddleName: ', BirthDate: ' , EmailAddress: ', ZIPCODE: ', Citizenservicenumber: ', City: ', Gender: ', PhoneNumber: ', Street: '} '; 34 This.myPatientService.httpPutExample (ID, this.mypatient). Then (_ = = This.getall ());}36 Notoginseng Httppatchexample (i D:string, firstname:string, lastname:string) {this.mypatient = new Patient ({id: ', firstname:firstname, L Astname:lastname}); This.myPatientService.httpPatchExample (ID, this.mypatient). Then (_ = This.getall ()); 40 }41 Delbyid (id:string) {This.myPatientService.delbyID (ID). Then (_ = = This.getall ()); 44}45}
Service Code
1 Import {injectable} from ' @angular/core '; 2 Import {HttpClient, Httpparams, httpheaders} from ' @angular/common/http '; 3 4 Export class Patient {5 id:string; 6 firstname:string; 7 lastname:string; 8 middlename:string; 9 birthdate:string; Ten gender:string; One by one phonenumber:string; zipcode:string; city:string; street:string; emailaddress:string; citizenservicenumber:string; Constructor public: {id:string, FirstName?: String, 22 LastName: String, MiddleName?: String, BirthDate?: String, Gender?: String, PhoneNumber?: String, ZIPCODE?: String, City?: String, 29 Street?: String, EmailAddress?: String, Citizenservicenumber?: String 32}) {33 if (fields) object.assign (this, fields);Getfullname (): string {PNS return this. FirstName + "+ this. LastName; () @Injectable () () Patientservice () Export class {mypatientlist:patient[] = []; Ypatient:patient = null; Mywebapiurl = ' http://localhost:52513/api/patients/'; Myhttphead = {Headers:new httpheaders ({' Content-type ': ' Application/json '})}; Myhttpparams = new Httpparams (). Set (' username ', ' dih '). Set (' Password ', ' dih '); Constructor (private myhttp:httpclient) {} setpatient (Data:any): Patient {return new Patie NT ({id:data[' Patientid '], firstname:data[' Details '). FirstName, lastname:data[' Details ']. LastName, middlename:data[' Details ']. MiddleName, birthdate:data[' Details ']. BirthDate, gender:data[' Details ']. Gender, phonenumber:data[' Personalinfo '). Phonenumberprimary, 61 zipcode:data[' Personalinfo '. ZIPCODE, city:data[' Personalinfo ']. City, street:data[' Personalinfo ']. Street, emailaddress:data[' Personalinfo '). Emailaddressprimary, citizenservicenumber:data[' Personalinfo ']. Servicenumber 66}); GetAll (): promise<patient[]> {this.mypatientlist = []; return this.myhttp . Get (This.mywebapiurl). Topromise (). then (data = = (<array<string>>data). length; (var i = 0; i < count; i++) {This.myPatientList.push (This.setpatient (Data[i])); This.mypatientlist return; ). catch (Error = (Console.log (error))); (id:string): promise<patient> {getbyId return This.myhttp.get (This.mywebapiurl + ID) . topromise (). Then (data + = This.mypatient = this.)Setpatient (data); This.mypatient return; 86}); (patient:patient, id:string = "): Any {setpatientbody return {" Patientid ": I D, "Details": {"FirstName": patient. FirstName, "LastName": patient. LastName, 94 "Maidenname": "," MiddleName ":", "Customid": ", 97 "BirthDate": "2017-10-18t11:05:51.017", 98 "Gender": 1},100 "A Natomy ": {101" bodyweight ": 75,102" bodyheight ": 175,103" Leftfootlength ": 0,104 "Rightfootlength": 0,105 "stridelengthwalking": 0,106 "stridelength Running ": 0,107" pelviswidth ": 0,108" leftupperleglength ": 0,109" Rightupp Erleglength ": 0,110" leftlowerleglength ": 0,111 "Rightlowerleglength": 0112},113 "Personalinfo": {"Servicenumber" : "," emailaddressprimary ":" [email protected] "," emailaddresssecondary ":", 1 "Phonenumberprimary": ", 118" phonenumbersecondary ":", 119 "streetaddr ESS ":", "ZIPCode": ", 121" City ":", 122 "Street": ", 123 "Country": ", 124" emergencycontactdetails ":"},126 "Additionalpropertie S ": ' 127};128}129 httppostexample (patient:patient): promise<any> {131 Const BODY = t His.setpatientbody (patient); This.myhttp.post return (This.mywebapiurl, body, this.myhttphead). Topromise (); 133 }134 135 httpputexample (id:string, patient:patient) {136 Const BODY = This.setpatientbody (patient, id); 13 7 Return this.myHttp.put (This.mywebapiurl + ID, body, this.myhttphead). Topromise (); 138}139-Httppatchexample (id:string, Patie Nt:patient) {141 Const BODY = {142 "Patientid": id,143 "Details": {144 "F Irstname ": Patient. firstname,145 "LastName": patient. LastName146},147 "Anatomy": {148 "bodyweight": 111,149 "Bodyheigh T ": 175150}151};152 return This.myhttp.patch (This.mywebapiurl + ID, body, this.myhttphead). t Opromise (); 153}154 155 Delbyid (id:string): promise<boolean> {156 return This.myhttp.delete (this.my Webapiurl + ID). topromise (); 157}158}
Increase the processing of the return value: "Then there are two parameters, one is the correct return value, one is the wrong return value, the server returns the result of the error, the result is obtained through err.error.Message, or the direct output of all err himself point to see."
This.myPatientService.httpPutExample (ID, this.mypatient). Then ( result = = { This.getall (); }, Err = > { console.error (err.error.Message); This.getall (); } )
Error message returned by the server:
Error message received by the client:
The HTML page does not change:
<div>patient-component.html</div>{{results}}<button (click) = "Httppatchexample (txt1.value,txtfirstname.value,txtlastname.value)" > httppatchexample "Modify" </button>
</div>
Transferred from: http://www.cnblogs.com/cxd1008/p/7778948.html
Angular HttpClient post put patch del method (2)-promise service