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: ‘patient-component‘,
  7     templateUrl: ‘app/app-patient/patient.component.html‘,
  8     //providers: [PatientsService]
  9 })
 10 export class PatientComponent implements OnInit {
 11
 12     results: string[];
 13     myPatientList: Patient[] = [];
 14     myPatient: Patient;
 15     myWebapiURL = ‘http://localhost:52513/api/patients/‘;
 16     myHttpHead = { headers: new HttpHeaders({ ‘Content-Type‘: ‘application/json‘ }) };
 17     private myHttpParams = new HttpParams().set(‘username‘, ‘dih‘).set(‘password‘, ‘dih‘);
 18     constructor
 19         (
 20         private myhttp: HttpClient
 21         //private myPatientsService: PatientsService
 22         )
 23     { }
 24     ngOnInit(): void {
 25         this.results = ["ngOnInit()方法"];
 26         this.getall();
 27     }
 28     getall() {
 29         //console.log("getall");
 30         this.myPatientList = [];
 31         this.myhttp.get(this.myWebapiURL)
 32             .subscribe(data => {
 33                 let count = (<Array<string>>data).length;
 34                 for (var i = 0; i < count; i++) {
 35
 36                     this.myPatientList.push(new Patient({
 37                         id: data[i].PatientId,
 38                         FirstName: data[i].Details.FirstName,
 39                         LastName: data[i].Details.LastName,
 40                         MiddleName: data[i].Details.MiddleName,
 41                         BirthDate: data[i].Details.BirthDate,
 42                         Gender: data[i].Details.Gender,
 43                         PhoneNumber: data[i].PersonalInfo.PhoneNumberPrimary,
 44                         ZIPCODE: data[i].PersonalInfo.ZIPCODE,
 45                         City: data[i].PersonalInfo.City,
 46                         Street: data[i].PersonalInfo.Street,
 47                         EmailAddress: data[i].PersonalInfo.EmailAddressPrimary,
 48                         CitizenServiceNumber: data[i].PersonalInfo.ServiceNumber
 49                     }));
 50                 }
 51             }
 52             );
 53     }
 54
 55
 56     getbyId(id: string) {
 57         this.myhttp.get(this.myWebapiURL + id)
 58             .subscribe(data => {
 59                 this.myPatient = new Patient({
 60                     id: data[‘PatientId‘],
 61                     FirstName: data[‘Details‘].FirstName,
 62                     LastName: data[‘Details‘].LastName,
 63                     MiddleName: data[‘Details‘].MiddleName,
 64                     BirthDate: data[‘Details‘].BirthDate,
 65                     Gender: data[‘Details‘].Gender,
 66                     PhoneNumber: data[‘PersonalInfo‘].PhoneNumberPrimary,
 67                     ZIPCODE: data[‘PersonalInfo‘].ZIPCODE,
 68                     City: data[‘PersonalInfo‘].City,
 69                     Street: data[‘PersonalInfo‘].Street,
 70                     EmailAddress: data[‘PersonalInfo‘].EmailAddressPrimary,
 71                     CitizenServiceNumber: data[‘PersonalInfo‘].ServiceNumber
 72                 });
 73             });
 74     }
 75
 76
 77
 78     httpPostExample(FirstName: string, LastName: string) {
 79         const body = {
 80             "Details": {
 81                 "FirstName": FirstName,
 82                 "LastName": LastName,
 83                 "MaidenName": ‘‘,
 84                 "MiddleName": ‘‘,
 85                 "CustomId": ‘‘,
 86                 "BirthDate": "2017-10-18T11:05:51.017",
 87                 "Gender": 1
 88             },
 89             "Anatomy": {
 90                 "BodyWeight": 75,
 91                 "BodyHeight": 175,
 92                 "LeftFootLength": 0,
 93                 "RightFootLength": 0,
 94                 "StrideLengthWalking": 0,
 95                 "StrideLengthRunning": 0,
 96                 "PelvisWidth": 0,
 97                 "LeftUpperLegLength": 0,
 98                 "RightUpperLegLength": 0,
 99                 "LeftLowerLegLength": 0,
100                 "RightLowerLegLength": 0
101             },
102             "PersonalInfo": {
103                 "ServiceNumber": ‘‘,
104                 "EmailAddressPrimary": "[email protected]",
105                 "EmailAddressSecondary": ‘‘,
106                 "PhoneNumberPrimary": ‘‘,
107                 "PhoneNumberSecondary": ‘‘,
108                 "StreetAddress": ‘‘,
109                 "ZIPCode": ‘‘,
110                 "City": ‘‘,
111                 "Street": ‘‘,
112                 "Country": ‘‘,
113                 "EmergencyContactDetails": ‘‘
114             },
115             "AdditionalProperties": ‘‘
116         };
117         this.myhttp.post(this.myWebapiURL, body, this.myHttpHead)
118             .subscribe(
119             (val) => {
120                 console.log(‘POST call successful value returned in body‘, val);
121                 this.getall();
122             },
123             response => {
124                 console.log(‘POST call in error‘, response);
125             },
126             () => {
127                 console.log(‘The POST observable is now completed.‘);
128             });
129
130     }
131
132     httpPutExample(id: string, FirstName: string, LastName: string) {
133         const body = {
134             "PatientId": id,
135             "Details": {
136                 "FirstName": FirstName,
137                 "LastName": LastName,
138                 "MaidenName": ‘‘,
139                 "MiddleName": ‘‘,
140                 "CustomId": ‘‘,
141                 "BirthDate": "2017-10-18T11:05:51.017",
142                 "Gender": 1
143             },
144             "Anatomy": {
145                 "BodyWeight": 75,
146                 "BodyHeight": 175,
147                 "LeftFootLength": 0,
148                 "RightFootLength": 0,
149                 "StrideLengthWalking": 0,
150                 "StrideLengthRunning": 0,
151                 "PelvisWidth": 0,
152                 "LeftUpperLegLength": 0,
153                 "RightUpperLegLength": 0,
154                 "LeftLowerLegLength": 0,
155                 "RightLowerLegLength": 0
156             },
157             "PersonalInfo": {
158                 "ServiceNumber": ‘‘,
159                 "EmailAddressPrimary": "[email protected]",
160                 "EmailAddressSecondary": ‘‘,
161                 "PhoneNumberPrimary": ‘‘,
162                 "PhoneNumberSecondary": ‘‘,
163                 "StreetAddress": ‘‘,
164                 "ZIPCode": ‘‘,
165                 "City": ‘‘,
166                 "Street": ‘‘,
167                 "Country": ‘‘,
168                 "EmergencyContactDetails": ‘‘
169             },
170             "AdditionalProperties": ‘‘
171         };
172         this.myhttp.put(this.myWebapiURL + id, body, this.myHttpHead)
173             .subscribe(
174             (val) => {
175                 console.log(‘put call successful‘, val);
176                 this.getall();
177             },
178             response => {
179                 console.log(‘put call in error‘, response);
180             },
181             () => {
182                 console.log(‘put is now completed.‘);
183             });
184
185     }
186
187
188     delbyId(id: string) {
189         this.myhttp.delete(this.myWebapiURL + id).subscribe((res) => {
190             console.log("del ok", res);
191             this.getall();
192         }, (err) => {
193             console.log("del err", err);
194         });
195
196     }
197 }

前台代码:

 1 <div>patient-component.html</div>
 2
 3
 4 {{results}}
 5
 6 <h2>ngfor</h2>
 7 <div *ngIf=myPatientList>
 8     <ul>
 9         <li *ngFor="let myPatient of myPatientList">
10             id:<span style="font-weight:700"> {{myPatient.id}} </span> FirstName :{{myPatient.FirstName}}
11         </li>
12     </ul>
13
14 </div>
15 <div>
16     <input type="text" #txt1 placeholder="请输入要查询的GUID">
17     <button (click)="getbyId(txt1.value)"> 查询</button>
18     <button (click)="delbyId(txt1.value)"> 删除</button>
19
20
21     <div *ngIf=myPatient>
22         <ul>
23             <li>id:{{myPatient.id}}</li>
24             <li>FirstName :{{myPatient.FirstName}} </li>
25             <li>email:{{myPatient.EmailAddress}}</li>
26         </ul>
27     </div>
28 </div>
29 <div>
30     FirstName :<input type="text" #txtFirstName placeholder="请输入FirstName">
31     LastName :<input type="text" #txtLastName placeholder="请输入LastName">
32     <button (click)="httpPostExample(txtFirstName.value,txtLastName.value)"> httpPostExample【新增】</button>
33     <button (click)="httpPutExample(txt1.value,txtFirstName.value,txtLastName.value)"> httpPutExample【修改】</button>
34
35 </div>

。。。。。。。。angular4.3 httpclient end.....

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

时间: 2024-08-29 14:54:29

angular HttpClient post put del 方法的相关文章

httpclient 4.3 psot方法上传文件与参数 中文乱码解决

废话不多说,直接上有码的! 1 package httpclient; 2 3 import java.io.File; 4 import java.nio.charset.Charset; 5 6 import org.apache.http.Consts; 7 import org.apache.http.Header; 8 import org.apache.http.HttpEntity; 9 import org.apache.http.client.methods.Closeable

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 i

单例模式和angular的services的使用方法

在现实生活中存在着有这样的特点的一些类: A.这些类只能有一个实例: B.这些能够自动实例化: C.这个类对整个系统可见,即必须向整个系统提供这个实例. 不妨举一个具体的单例模式的例子:比如教室里面的教师和学生都是需要在黑板上写字的,但是一般的情况下,教室里面应该只有一个黑板吧,它是教师和学生公用滴.这时就要想办法保证取得的黑板是一个共享的唯一的对象.而单例模式就是解决这类问题的一个已经成型的模式. Angular带来了很多类型的services.每个都会它自己不同的使用场景.我们将在本节来阐述

Android中利用httpclient进行网络通信的方法(以用户登录为例说明)

http://www.android100.org/html/201406/09/22915.html 1.服务器端 服务器端和android没有太大关系,对J2EE比较熟悉的话写起来应该很容易,这里就不一一贴出代码. 首先在本地创建一个数据库表,其中包含了一个userinfo表用来存储用户信息. 需要实现的代码如下: DBUtils:创建数据库连接对象 User实体类:用来存放用户信息 UserDao:用来对处理User相关的数据操作 UserService:调用UserDao来处理事务 Us

httpclient测试get post方法时报错Class not found com.xh.httpclient.HttpClientTest

Class not found com.xh.httpclient.HttpClientTest java.lang.ClassNotFoundException: com.xh.httpclient.HttpClientTest at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Lau

python:remove,pop和del方法的区别

remove remove(item)方法是直接对可变序中的元素进行检索删除,返回的是删除后的列表,不返回删除值(返回None) list1=[1,3,6,7,8] print list1.remove(3) #对列表元素进行搜索删除,而不是下表 print list1 None [1,6,7,8] pop pop(index)方法是对可变序列中元素下标进行检索删除,返回删除值 list1=[1,3,6,7,8] print list1.pop(3),#对列表下表进行检索删除 print lis

对HttpClient实现的 HTTP 方法中get、post有无参数方法抽取一个公共类

/** * 抽取一个公共的类 * * @author xz * */ @Service public class ApiService { @Autowired private RequestConfig config; @Autowired private CloseableHttpClient httpClient; /** * 无参的get请求 * * @param url * @return */ public String doGet(String url) { // HttpGet对

HttpClient GET POST DELETE方法使用

package com.xiaobudian.childarticle.util; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMeth

Angular过滤器 自定义及使用方法

首先设置自定义过滤器. 定义模块名:angular .module('myApp') .filter('filterName',function(){ return function(要过滤的对象,参数1,参数2,...){ return Obj; //这里返回的是过滤后的对象 } }); 页面中的使用 {{obj | filterName}} ====> obj是要过滤的对象 控制器中使用. 首先要要控制器注入$filter $filter("filterName")(要过滤的