ionic 基础封装 网络请求
开发中常用的网络请求有get post 因为大量重复使用, 所以创建一个基类.
创建关于网络请求的 使用命令 : ionic g service http/http
-
在 src 路径下生成一个关于 http 文件夹, 在里面搭建http 服务
使用命令提示 ionic g service http/http
屏幕快照 2019-05-05 下午8.41.16.png
开始搭建网络请求
- constructor 里面导入
// 必须要注意导入的路径 不要错了 , 错了你再回来看就好了
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
- 还需要在 appModule 里面加入 不加入的时候就会... 你试试呗
import { HttpClientModule } from '@angular/common/http';
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule],
- 开始创建 网络请求的公共header , 大部分的公司网络请求头部都是传一些公共固定的东西 , 这个需要大家结合自己的实际情况来做的
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json', // get 请求的时候无效
'Accept': 'application/json, text/plain, */*',
'deviceid' : '123',
'appversion' : '1.0.0',
'devicetype' : 'ios',
// 这里将 登录 token 传入进来, 有就传值, 没有就不传值 , 那么判断需不需要这个值, 用户是否登录 就在实际调用方法的时候 做判断就好了
'token' : window.localStorage.getItem('token') ? `${window.localStorage.getItem('token') }` : ''
})
};
post 网络请求
这个代码上来说 比较快
/**
* post 网络请求
* @param url 网络请求的地址
* @param params 需要传入的参数
*
* @return Observable<字典>
*/
POST_request(url: string, params ?: {}): Observable<any> {
const body = JSON.stringify(params);
return this.http.post(url, body, this.httpOptions);
}
get 请求的封装
这个比较复杂 , 因为需要将 params 里面的字段 拼接到url 里面
/**
* 1. 基础方法 拼接字符串
* 需要传递的字符串 传入字典
* @param {{[key: string] : string}} Dict
* @memberof BaseFunction
*/
mosaicJsonWithDict(Dict: {[key: string]: string}): string {
let bodyString = ``;
for (const key in Dict) {
if (Dict.hasOwnProperty(key)) {
const element = Dict[key];
bodyString = bodyString + key + '=' + element + '&';
}
}
bodyString = bodyString.substring(0, bodyString.length - 1);
return bodyString;
}
/**
* get 网络请求
* @param url
* @param param
*/
GET_request(url: string, param?: {}): Observable<any> {
if (param) {
url = this.mosaicJsonWithDict(param);
}
return this.http.get(url, this.httpOptions);
}
还有可以加上网络请求缓存, 提高用户体验.
使用
- 需要在 appModule 里面注入HttpService
import { HttpService } from './http/http.service';
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
HttpService
],
- 使用在 constructor(private http: HttpService) { }
// 这里是获取首页轮播的方法 , 选传的字段可以不传
this.http.GET_request('http://192.168.100.7:8080/api/homeBanner?').subscribe(data => {
console.log(data); // 具体数据 具体处理
}, error => {
console.log(error);;
});
const params = {
'name' : 'summer',
'password' : '123456' // 你们怎么加密就怎么加密 不会这么明文传输的
};
this.http.POST_request('http://192.168.100.7:8080/api/user/login?', params).subscribe(data => {
console.log(data);
}, error => {
console.log(error);
});
就介绍到这里的 , 剩下的就是数据的处理了 , 这个需要看具体公司的 具体返回的数据信息
网友评论