新建http provider
ionic g provider httpSer
import { HttpClient ,HttpHeaders} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ToastController ,AlertController} from 'ionic-angular';
/*
Generated class for the HttpSerProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class HttpSerProvider {
constructor(
public http: HttpClient,
public toastCtrl: ToastController,
public alertCtrl: AlertController
) {
}
public url:string = 'http://xxx.com'
//彈層
public toast(message,duration) {
const toast = this.toastCtrl.create({
message: message,
duration: duration
});
toast.present();
}
GET(urlmethod , callback ?: (res: any, error: any) => void): void {
this.http.get(this.url + '' + urlmethod + '').subscribe(data =>{
callback && callback(data, null);
},err =>{
callback && callback(null, err);}
)
}
POST(data, urlmethod , callback ?: (res: any, error: any) => void): void {
const headers = new HttpHeaders().set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
this.http.post(this.url + '' + urlmethod + '', this.toQueryString(data), {headers})
.subscribe(res => {
callback && callback(res, null);
},err =>{
callback && callback(null, err);
}
)}
// 序列化
private toQueryString(obj) {
let result = [];
for (let key in obj) {
key = encodeURIComponent(key);
let values = obj[key];
if (values && values.constructor == Array) {
let queryValues = [];
for (let i = 0, len = values.length, value; i < len; i++) {
value = values[i];
queryValues.push(this.toQueryPair(key, value));
}
result = result.concat(queryValues);
} else {
result.push(this.toQueryPair(key, values));
}
}
return result.join('&');
}
private toQueryPair(key, value) {
if (typeof value == 'undefined'){
return key;
}
return key + '=' + encodeURIComponent(value === null ? '' : String(value));
}
}
使用的頁面引入
import { HttpSerProvider } from '../../providers/http-ser/http-ser';
constructor中注入
constructor(
public httpser :HttpSerProvider
) {}
get請求
this.httpser.GET('/xxx',(res,err)=>{
if(err){
return
}
conlose.log(res);
this.httpser.toast('成功',2000)
})
post請求
let obj ={
'name':'NBHH'茄厘,
'age':'18'
}
this.httpser.POST(obj,'/xxx',(res,err)=>{
if(err){
return
}
console.log(res);
this.httpser.toast('成功',2000)
})