angular $q封装$http get和post请求

  

//第一步,定义发送请求的配置信息

angular.module('hkApp')
.constant('API_ENDPOINT', {
	host: 'http://testfx.ypcoo.com',
	port: 80,
	path: '/index.php/Wap',
	platform: 'weixin' // string 'weixin or app' 平台常量,通过此参数判断系统是在微信里面使用还是在APP里面使用,以便调用不同的微信接口
});

//第二步,定义一个服务,“专门”用来发送get或者post请求

/**
 * 定义ApiService服务
 * 功能:专门向服务器发送post 和 get请求
 * */
angular.module('hkApp')
	.factory('ApiService', ["$window", "$http", "WAP_CONFIG", "$q", "$log","$ionicLoading",function($window, $http, WAP_CONFIG, $q, $log,$ionicLoading) {
		var _api = WAP_CONFIG;
		var endpoint = _api.host + ':' + _api.port;

		// public api
		return {
			//发送服务器的域名+端口,例如http://deve.sqhzg.cn:80
			endpoint: endpoint,

			//post请求,第一个参数是URL,第二个参数是向服务器发送的参数(JSON对象),
			post: function(url, data) {
				url = endpoint + url;
				var deferred = $q.defer();
				var tempPromise;
				//显示加载进度
				$ionicLoading.show({
					template: 'Loading...'
				});
				//判断用户是否传递了参数,如果有参数需要传递参数
				if(data != null && data != undefined && data != ""){
					tempPromise = $http.post(url,data);
				}else{
					tempPromise = $http.post(url);
				}
				tempPromise.success(function(data,header,config,status) {
					deferred.resolve(data);
					$ionicLoading.hide();
				}).error(function(msg, code) {
					deferred.reject(msg);
					$log.error(msg, code);
					$ionicLoading.hide();
				});
				return deferred.promise;
			},

			//get请求,第一个参数是URL,第二个参数是向服务器发送的参数(JSON对象),
			get: function(url, data) {
				url = endpoint + url;
				var deferred = $q.defer();
				var tempPromise;
				//显示加载进度
				$ionicLoading.show({
					template: 'Loading...'
				});
				//判断用户是否传递了参数,如果有参数需要传递参数
				if(data != null && data != undefined && data != ""){
					tempPromise = $http.get(url,data);
				}else{
					tempPromise = $http.get(url);
				}
				tempPromise.success(function(data,header,config,status) {
					deferred.resolve(data);
					$ionicLoading.hide();
				}).error(function(msg, code) {
					deferred.reject(msg);
					$ionicLoading.hide();
					$log.error(msg, code);
				});
				return deferred.promise;
			}
		};

	}]);

备注:在请求前添加了$ionicLoading显示,请求返回之后,因此$ionicLoading对象。当遇到服务器压力大的时候,不会出现“白屏” 的情况,提高用户体验 

//控制器注入服务,发送请求

.state('index',{
	url:'/app_index',
	templateURL: 'ABC.html',
	onEnter :function(){
		//因此底部的导航栏
		$(".index_footer").show();
	},
	controller:["$scope","$state",'$ionicActionSheet',"setting_user_levelService","userNameService","ApiService",function($scope,$state,$ionicActionSheet,setting_user_levelService,userNameService,ApiService){
		//获取用户信息
		var userInfoPromise = ApiService.post("{:U('UserInfo/getUser')}",{
					"id": "{$Think.session.ADMINID}"
					});
		
		userInfoPromise.then(function(response){
			if(response.status == 1){
				//会员名称
				$scope.typetext = response.data.typetext;
				//积分
				$scope.jifen = response.data.jifen;
				//红包
				$scope.redpacket = response.data.redpacket;
			}
		});
		
	}]
})

猜你喜欢

转载自hbiao68.iteye.com/blog/2304592