angular HttpClient post put patch del 方法(2)-Promise 服务

前做了在一个页面的CRUD的方法,现实中webapi模块往往是单独写服务的,所以修改了一下原来的设计和结构,还是需要很多知识的。

2017.11.15增加patch方法 ,改进服务程序优化写法

2017.11.27增加Promise返回值处理,服务器返回错误信息后的处理.

因为所有的CRUD方法 都写在服务中,所以后台的代码就简单多了,回调还需要详细信息什么的,总之已经能运行正常了:

复制代码
 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 {
10     results: string[];
11     myPatientList: Patient[] = [];
12     myPatient: Patient = null;
13     constructor(private myPatientService: PatientService)
14     { }
15     ngOnInit(): void {
16         this.results = ["ngOnInit()方法"];
17         this.getall();
18     }
19     getall() {
20         this.myPatientService.getall().then(data => this.myPatientList = data);
21     }
22 
23     getbyId(id: string) {
24         this.myPatientService.getbyId(id).then(data => this.myPatient = data);
25     }
26 
27     httpPostExample(FirstName: string, LastName: string) {
28         this.myPatient = new Patient({ id: '', FirstName: FirstName, LastName: LastName, MiddleName: '', BirthDate: '', EmailAddress: '', ZIPCODE: '', CitizenServiceNumber: '', City: '', Gender: '' });
29         //使用then方法等待返回结果,并进一步处理业务需求。then相当入一个回调函数。
30         this.myPatientService.httpPostExample(this.myPatient).then(_ => this.getall());
31     }
32     httpPutExample(id: string, FirstName: string, LastName: string) {
33         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());
35     }
36 
37     httpPatchExample(id: string, FirstName: string, LastName: string) {
38         this.myPatient = new Patient({ id: '', FirstName: FirstName, LastName: LastName });
39         this.myPatientService.httpPatchExample(id, this.myPatient).then(_ => this.getall());
40     }
41 
42     delbyId(id: string) {
43         this.myPatientService.delbyId(id).then(_ => this.getall());
44     }
45 }
复制代码

服务代码

复制代码
  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;
 10     Gender: string;
 11     PhoneNumber: string;
 12     ZIPCODE: string;
 13     City: string;
 14     Street: string;
 15     EmailAddress: string;
 16     CitizenServiceNumber: string;
 17 
 18     public constructor(
 19         fields?: {
 20             id: string,
 21             FirstName?: string,
 22             LastName?: string,
 23             MiddleName?: string,
 24             BirthDate?: string,
 25             Gender?: string,
 26             PhoneNumber?: string,
 27             ZIPCODE?: string,
 28             City?: string,
 29             Street?: string,
 30             EmailAddress?: string,
 31             CitizenServiceNumber?: string
 32         }) {
 33         if (fields) Object.assign(this, fields);
 34     }
 35 
 36     getFullName(): string {
 37         return this.FirstName + ' ' + this.LastName;
 38     }
 39 
 40 
 41 }
 42 @Injectable()
 43 export class PatientService {
 44 
 45     myPatientList: Patient[] = [];
 46     myPatient: Patient = null;
 47     myWebapiURL = 'http://localhost:52513/api/patients/';
 48     myHttpHead = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
 49     private myHttpParams = new HttpParams().set('username', 'dih').set('password', 'dih');
 50     constructor(private myhttp: HttpClient) { }
 51 
 52     setPatient(data: any): Patient {
 53         return new Patient({
 54             id: data['PatientId'],
 55             FirstName: data['Details'].FirstName,
 56             LastName: data['Details'].LastName,
 57             MiddleName: data['Details'].MiddleName,
 58             BirthDate: data['Details'].BirthDate,
 59             Gender: data['Details'].Gender,
 60             PhoneNumber: data['PersonalInfo'].PhoneNumberPrimary,
 61             ZIPCODE: data['PersonalInfo'].ZIPCODE,
 62             City: data['PersonalInfo'].City,
 63             Street: data['PersonalInfo'].Street,
 64             EmailAddress: data['PersonalInfo'].EmailAddressPrimary,
 65             CitizenServiceNumber: data['PersonalInfo'].ServiceNumber
 66         });
 67     }
 68 
 69     getall(): Promise<Patient[]> {
 70         this.myPatientList = [];
 71         return this.myhttp.get(this.myWebapiURL).toPromise().then(data => {
 72             let count = (<Array<string>>data).length;
 73             for (var i = 0; i < count; i++) {
 74                 this.myPatientList.push(this.setPatient(data[i]));
 75             }
 76             return this.myPatientList;
 77         }
 78         ).catch(error => (console.log(error)));
 79     }
 80 
 81     getbyId(id: string): Promise<Patient> {
 82         return this.myhttp.get(this.myWebapiURL + id).toPromise()
 83             .then(data => {
 84                 this.myPatient = this.setPatient(data);
 85                 return this.myPatient;
 86             });
 87     }
 88     setPatientBody(patient: Patient, id: string = ''): any {
 89         return {
 90             "PatientId": id,
 91             "Details": {
 92                 "FirstName": patient.FirstName,
 93                 "LastName": patient.LastName,
 94                 "MaidenName": '',
 95                 "MiddleName": '',
 96                 "CustomId": '',
 97                 "BirthDate": "2017-10-18T11:05:51.017",
 98                 "Gender": 1
 99             },
100             "Anatomy": {
101                 "BodyWeight": 75,
102                 "BodyHeight": 175,
103                 "LeftFootLength": 0,
104                 "RightFootLength": 0,
105                 "StrideLengthWalking": 0,
106                 "StrideLengthRunning": 0,
107                 "PelvisWidth": 0,
108                 "LeftUpperLegLength": 0,
109                 "RightUpperLegLength": 0,
110                 "LeftLowerLegLength": 0,
111                 "RightLowerLegLength": 0
112             },
113             "PersonalInfo": {
114                 "ServiceNumber": '',
115                 "EmailAddressPrimary": "abc@a.com",
116                 "EmailAddressSecondary": '',
117                 "PhoneNumberPrimary": '',
118                 "PhoneNumberSecondary": '',
119                 "StreetAddress": '',
120                 "ZIPCode": '',
121                 "City": '',
122                 "Street": '',
123                 "Country": '',
124                 "EmergencyContactDetails": ''
125             },
126             "AdditionalProperties": ''
127         };
128     }
129 
130     httpPostExample(patient: Patient): Promise<any> {
131         const body = this.setPatientBody(patient);
132         return this.myhttp.post(this.myWebapiURL, body, this.myHttpHead).toPromise();
133     }
134 
135     httpPutExample(id: string, patient: Patient) {
136         const body = this.setPatientBody(patient, id);
137         return this.myhttp.put(this.myWebapiURL + id, body, this.myHttpHead).toPromise();
138     }
139 
140     httpPatchExample(id: string, patient: Patient) {
141         const body = {
142             "PatientId": id,
143             "Details": {
144                 "FirstName": patient.FirstName,
145                 "LastName": patient.LastName
146             },
147             "Anatomy": {
148                 "BodyWeight": 111,
149                 "BodyHeight": 175
150             }
151         };
152         return this.myhttp.patch(this.myWebapiURL + id, body, this.myHttpHead).toPromise();
153     }
154 
155     delbyId(id: string): Promise<boolean> {
156         return this.myhttp.delete(this.myWebapiURL + id).toPromise();
157     }
158 }
复制代码

增加返回值的处理:【then后有两个参数,一个是正确的返回值,一个是错误的返回值,服务器返回错误的结果后,通过err.error.Message 取得结果,或者直接输出全部err自己点着看.】

复制代码
        this.myPatientService.httpPutExample(id, this.myPatient).then(
            result => {
                this.getall();
            }, err => {
                console.error(err.error.Message);
                this.getall();
            }
        )
复制代码

服务器返回的错误信息:

客户端接收的错误信息:

html页面没有变化:

复制代码
<div>patient-component.html</div>
{{results}}
<h2>ngfor</h2>
<div *ngIf=myPatientList>
    <ul>
        <li *ngFor="let myPatient of myPatientList">
            id:<span style="font-weight:700"> {{myPatient.id}} </span> FirstName :{{myPatient.FirstName}}
        </li>
    </ul>
</div>
<div>
    <input type="text" #txt1 placeholder="请输入要查询的GUID">
    <button (click)="getbyId(txt1.value)"> 查询</button>
    <button (click)="delbyId(txt1.value)"> 删除</button>
    <div *ngIf=myPatient>
        <ul>
            <li>id:{{myPatient.id}}</li>
            <li>FirstName :{{myPatient.FirstName}} </li>
            <li>email:{{myPatient.EmailAddress}}</li>
        </ul>
    </div>
</div>
<div>
    FirstName :<input type="text" #txtFirstName placeholder="请输入FirstName">
    LastName :<input type="text" #txtLastName placeholder="请输入LastName">
    <button (click)="httpPostExample(txtFirstName.value,txtLastName.value)"> httpPostExample【新增】</button>
    <button (click)="httpPutExample(txt1.value,txtFirstName.value,txtLastName.value)"> httpPutExample【修改】</button>
<button (click)="httpPatchExample(txt1.value,txtFirstName.value,txtLastName.value)"> httpPatchExample【修改】</button>
</div>
复制代码

 转自:http://www.cnblogs.com/cxd1008/p/7778948.html

原文地址:https://www.cnblogs.com/yangfantianxia/p/8053291.html