请先查看上一篇文章HttpClient配置,之后在进行。
使用
this.myhttp.get('http://192.168.2.139:9002/api/patients')方法,读取webapi。因为get方法是通过AJAX方法读取数据的,所以服务器要可以跨域访问,具体方法查询webapi文章
1 import { Component, OnInit } from '@angular/core'; 2 import { HttpClient } from '@angular/common/http'; 3 import { Patient } from './app.patient.server'; 4 @Component({ 5 selector: 'app-root', 6 templateUrl: './app.component.html', 7 styleUrls: ['./app.component.css'] 8 }) 9 10 export class AppComponent implements OnInit { 11 title = 'angular4.3'; 12 results: string[]; 13 myPatientList: Patient[] = []; 14 15 16 constructor( 17 private myhttp: HttpClient 18 ) { } 19 20 ngOnInit(): void { 21 this.myhttp.get('http://192.168.2.139:9002/api/patients') 22 .subscribe(data => { 23 this.myPatientList = (<any>data).map(u => new Patient({ 24 id: u.PatientId, 25 FirstName: u.Details.FirstName, 26 LastName: u.Details.LastName, 27 MiddleName: u.Details.MiddleName, 28 BirthDate: u.Details.BirthDate, 29 Gender: u.Details.Gender, 30 PhoneNumber: u.PersonalInfo.PhoneNumberPrimary, 31 ZIPCODE: u.PersonalInfo.ZIPCODE, 32 City: u.PersonalInfo.City, 33 Street: u.PersonalInfo.Street, 34 EmailAddress: u.PersonalInfo.EmailAddressPrimary, 35 CitizenServiceNumber: u.PersonalInfo.ServiceNumber 36 }));
37 38 }); 39 } 40 }
(<any>data).map()方法直接把读取data数据转换成实体类。
【注:需要查看自己的json文件,对应好结构】 网上很多json都是以results[]开头。以所用(<any>data).results.map() 这个问题真的卡了我很久,在同事长庆的帮助下才得以解决。
实体类代码,如下:
1 export class Patient { 2 id: string; 3 FirstName: string; 4 LastName: string; 5 MiddleName: string; 6 BirthDate: string; 7 Gender: string; 8 PhoneNumber: string; 9 ZIPCODE: string; 10 City: string; 11 Street: string; 12 EmailAddress: string; 13 CitizenServiceNumber: string; 14 15 public constructor( 16 fields?: { 17 id: string, 18 FirstName: string, 19 LastName: string, 20 MiddleName: string, 21 BirthDate: string, 22 Gender: string, 23 PhoneNumber: string, 24 ZIPCODE: string, 25 City: string, 26 Street: string, 27 EmailAddress: string, 28 CitizenServiceNumber: string 29 }) { 30 // tslint:disable-next-line:curly 31 if (fields) Object.assign(this, fields); 32 } 33 34 getFullName(): string { 35 return this.FirstName + ' ' + this.LastName; 36 } 37 }
前台调用很简单,直接读取实体类就可以了
1 <div style="text-align:center"> 2 <h1> 3 Welcome to {{title}}! 4 </h1> 5 {{results}} 6 <h2>ngfor</h2> 7 <ul> 8 <li *ngFor="let myPatient of myPatientList" > 9 id:{{myPatient.id}} FirstName :{{myPatient.FirstName}} 10 </li> 11 </ul> 12 </div>
显示如下图:
注:这个用法写的还很简单,还需要传参数,加头文件之类的方法,不过已经可以基本的读取数据了。
本文为博主原创文章,欢迎转载,但转载须注在明显位置注明【博客地址】和【原文地址】,否则将追究法律责任。http://www.cnblogs.com/cxd1008