Ionic4中的Get请求数据与Angular get 请求数据相同,那么是如何具体实现Get请求呢?
第一种方法:使用HttpClientModule模块
注意:Angular5.X以后get 与post请求服务器数据使用HttpClientModule模块。
① app.module.ts中引入并声明HttpClientModule
//引入http相关模块
import { HttpClientModule } from '@angular/common/http';
//声明
imports: [BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
HttpClientModule],
②建立公共http服务,用来保存常用的请求访问的地址
终端运行以下命令
ionic g service services/common
在common.service.ts引入 HttpClient
import { HttpClient } from '@angular/common/http';
在common.service.ts声明 HttpClient
constructor(public http:HttpClient) {}
在common.service.ts写入get请求的方法
export class CommonService {
public config:any={
domain:'http://192.168.22.XX:XXXX/'//接口公共部分
}
constructor(public http:HttpClient) {}//构造函数
ajaxGet(url){
var api=this.config.domain + url;
//回调函数
return new Promise ((resove,reject) =>{
this.http.get(api).subscribe((response)=>{
resove(response);
},(error)=>{
reject(error);
})
})
}
}
③具体page页面使用该方法
在具体的page引入http服务并声明
import { CommonService } from './../services/common.service';
在具体的page页面声明
//声明组件
constructor(
public common: CommonService
) { }
使用get方法获取用户的余额与姓名
//根据卡号,获取余额和姓名
QueryBalanceByCardId() {
var api = "OrderSystem/Card/QueryCash?cardno="+ window.localStorage.getItem('UserNameOnlyLastThreeNum');
this.common.ajaxGet(api).then((response) => {
this.person.money = response[0].cash;
this.person.name = response[0].ownerName;
})
}
后序分享其它两种get请求的方法。