打开cmd命令窗口,切换到项目目录分别执行下面命令:
ionic g provider config
ionic g provider HttpService
config
import { Platform } from 'ionic-angular'; import { Injectable } from '@angular/core'; /* Generated class for the ConfigProvider provider. See https://angular.io/guide/dependency-injection for more info on providers and Angular DI. */ @Injectable() export class ConfigProvider { //缓存key的配置 public cache: any = { slides: "_dress_slides", categories: "_dress_categories", products: "_dress_products" } public domain = "http://localhost:8014"; //接口地址 public API: any = { getCategories: '/api/ionic3/getCategories', getProducts: '/api/ionic3/getProducts', getDetails: '/api/ionic3/details', LoginAjax:'/WebApi/UserLogin/UserLogin.ashx',//登录接口 }; constructor(private platform: Platform) { console.log('Hello ConfigProvider Provider'); } /** * 是否真机环境 * @return {boolean} */ public isMobile(): boolean { return this.platform.is('mobile') && !this.platform.is('mobileweb'); } /** * 是否android真机环境 * @return {boolean} */ public isAndroid(): boolean { return this.isMobile() && this.platform.is('android'); } /** * 是否ios真机环境 * @return {boolean} */ public isIos(): boolean { return this.isMobile() && (this.platform.is('ios') || this.platform.is('ipad') || this.platform.is('iphone')); } }
http-service
import { Injectable } from '@angular/core'; import { Http, RequestOptions, Headers } from '@angular/http'; import { LoadingController, AlertController, ToastController, App } from 'ionic-angular'; import { URLSearchParams } from '@angular/http'; import { elementAt } from 'rxjs/operator/elementAt'; import { ConfigProvider } from '../../providers/config/config'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; /* Generated class for the HttpServiceProvider provider. See https://angular.io/guide/dependency-injection for more info on providers and Angular DI. */ @Injectable() export class HttpServiceProvider { //设置post的格式 private postheaders = new Headers({ 'Content-Type': 'application/json' }); constructor(public app: App, public http: Http, public loadingCtrl: LoadingController, private alertCtrl: AlertController, private toastCtrl: ToastController, private config: ConfigProvider) { console.log('Hello HttpServiceProvider Provider'); } // 对参数进行编码 encode(params) { var str = ''; if (params) { for (var key in params) { if (params.hasOwnProperty(key)) { var value = params[key]; str += encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&'; } } str = '?' + str.substring(0, str.length - 1); } return str; } //post提交参数便民 encodepost(params) { let param: URLSearchParams = new URLSearchParams(); if (params) { for (var key in params) { if (params.hasOwnProperty(key)) { param.set(key, params[key]); } } } return param; } //get请求带域名的 this.config.domain httpGet(url, params, callback, loader: boolean = false) { let loading = this.loadingCtrl.create({ content: "请稍后……", }); if (loader) { loading.present(); } this.http.get(this.config.domain + url + this.encode(params)) .toPromise() .then(res => { var d = res.json(); if (loader) { loading.dismiss(); } callback(d == null ? "[]" : d); }) .catch(error => { if (loader) { loading.dismiss(); } this.handleError(error); }); } //get请求不带域名的 this.config.domain httpGet2(url, params, callback, loader: boolean = false) { let loading = this.loadingCtrl.create({ content: "请稍后……", }); if (loader) { loading.present(); } this.http.get(url + this.encode(params)) .toPromise() .then(res => { var d = res.json(); if (loader) { loading.dismiss(); } callback(d == null ? "[]" : d); }) .catch(error => { if (loader) { loading.dismiss(); } this.handleError(error); }); } httpPost(url, params, callback, loader: boolean = false) { let loading = this.loadingCtrl.create({ content: "请稍后……", }); if (loader) { loading.present(); } let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }); //其实不表明 json 也可以, ng 默认好像是 json let options = new RequestOptions({ headers: headers }); this.http.post(this.config.domain + url, this.encodepost(params), options) .toPromise() .then(res => { var d = res.json(); if (loader) { loading.dismiss(); } callback(d == null ? "[]" : d); }).catch(error => { if (loader) { loading.dismiss(); } this.handleError(error); }); } private handleError(error: Response | any) { let msg = ''; if (error.status == 400) { msg = '请求无效(code:404)'; console.log('请检查参数类型是否匹配'); } if (error.status == 404) { msg = '请求资源不存在(code:404)'; console.error(msg + ',请检查路径是否正确'); } if (error.status == 500) { msg = '服务器发生错误(code:500)'; console.error(msg + ',请检查路径是否正确'); } console.log(error); if (msg != '') { this.toast(msg); } } alert(message, callback?) { if (callback) { let alert = this.alertCtrl.create({ title: '提示', message: message, buttons: [{ text: "确定", handler: data => { callback(); } }] }); alert.present(); } else { let alert = this.alertCtrl.create({ title: '提示', message: message, buttons: ["确定"] }); alert.present(); } } toast(message, callback?) { let toast = this.toastCtrl.create({ message: message, duration: 2000, dismissOnPageChange: true, }); toast.present(); if (callback) { callback(); } } //post 提交数据 doPost(apiUrl, json, callback) { var api = this.config.domain + apiUrl; this.http.post(api, JSON.stringify(json), { headers: this.postheaders }).subscribe(function (res) { callback(res.json()); }) } //存储到本地 setItem(key: string, obj: any) { try { var json = JSON.stringify(obj); localStorage.setItem(key, json); // window.localStorage[key] = json; } catch (e) { console.error("window.localStorage error:" + e); } } //从本地获取值 getItem(key: string, callback) { try { var json = localStorage[key]; var obj = ''; if (json != undefined) { obj = JSON.parse(json); } else { obj = null; } callback(obj); } catch (e) { console.error("window.localStorage error:" + e); } } getItems(key: string) { try { var json = localStorage[key]; var obj = JSON.parse(json); return obj; } catch (e) { console.error("window.localStorage error:" + e); } } removeItem(key) { localStorage.removeItem(key); } }