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": "[email protected]",
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

时间: 2024-07-28 16:18:48

angular HttpClient post put patch del 方法(2)-Promise 服务的相关文章

git patch生成方法

先把修改commit掉,然后生产修改patch给提交代码的同事,具体操作步骤如下: 修改代码的同事: git format-patch al821_xxx origin/al821_xxx 会生成:0001-HQ00656135-xxx-al821_xxx.patch这样的patch文件 把这个patch给提交代码的同事 提交代码的同事,执行: git am 0001-HQ00656135-xxx-al821_xxx.patch 然后可以检查这个提交记录有没有问题,如果没有问题 执行git pu

生成和打上patch的方法(转载)

原文链接:http://my.oschina.net/fgq611/blog/180750 在团队开发的过程中,经常需要生成patch,或者打上别人提供的patch,那么一般情况是如何操作的呢. 首先生成patch需要有两个工程,一个修改前的A工程,一个修改后的B工程. 使用linux命令diff就可以生成patch了.格式如下: 1 diff -Naur path/to/A_Project path/to/B_Project > Project.patch 注意:文件夹后面没有斜杠,即是 A_

C#下用select方法实现socket服务端

select是一种比较古老但一直被证明性能很好的socket模式,它可以让你以消息驱动的模式书写socket程序.网上C++的例子很多,但C#的例子极少. 上代码: namespace Server { class Program { // Thread signal. public static ManualResetEvent allDone = new ManualResetEvent(false); private static Socket handler = null; privat

win7 关于远程桌面登陆的方法,相应服务的启动

转自:http://blog.csdn.net/ningfuxuan/article/details/7519476 远程登陆电脑,对远程电脑的设置 (1)首先要启动远程电脑中的Remote Desktop Services  启动方法:在运行里输入services.msc ,然后启动.注意:没有设置之前默认登录为“此账户”,网络服务.此时不用修改.若不是的情况下,则可以点击浏览->高级->立即查找->在下面选择Network service即可,然后设置相应的密码. (2)在“我的电脑

angular HttpClient post put del 方法

直接上代码吧,之前的配置直接查看angular的前几篇文章. 后台TS代码: 1 import { Component, OnInit } from '@angular/core'; 2 import { Patient } from './patients.service'; 3 import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http'; 4 5 @Component({ 6 selector: 'pa

angular.fullpage.js指令的使用方法(详解)

接之前,jquery.fullpage在angular单页应用中存在重复初始化,分页器加倍问题,索性直接找到了angular.fullpage.js全屏滚动指令应用 angular-fullpage文档这里(将的不仔细自己做有点麻烦,不过有个demo) demo的却也不好看,直接上代码详解 1.首先得引用文件(当然angular.js必须的,省略) 2.导入angular.module内(fullPage.js放入,其他可以忽略自己用到的) 3. angular单页路由配置 state中加入(c

在Angular外部使用js调用Angular控制器中提供的函数方法或变量

Html代码如下所示: 1 <!DOCTYPE html> 2 <html ng-app="myApp" id="myApp"> 3 <head> 4 <meta name="viewport" content="width=device-width" /> 5 <title>Test</title> 6 <script src="~/Co

解决jinja2和angular的花括号{{}}冲突的方法。

一共3个方法, A.http://flask-triangle.readthedocs.org/en/develop/tutorial/part1.html 上代码 app.py from flask import Flask, render_template from flask.ext.triangle import Triangle     app = Flask(__name__, static_path='/static')     Triangle(app)     @app.rou

【JAVA】通过HttpClient发送HTTP请求的方法

HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 嵌入在 HTML 页面中的javascript 代码,猜测内容类型,重新格式化请求/重定向URI,或者其它和 HTTP 运输无关的功能. HttpClient使用 使用需要引入jar包,maven项目引入如下: 1 <dependency> 2 <groupId>org.apache