封装 Angular $http

作者:frank 发表日期:2016-09-23 12:23:22 更新日期:2016-09-23 12:23:22 分类:猿文色

摘要

封装 Angular $http

正文

平时使用 Angular 的 Http Service 需要先引用 $http,继而判断返回值是否正确。由于后台返回的数据格式都是固定的:比如 { ret: 'ok', data: [], msg: '' },每次请求完成都判断比较麻烦。

// 使用 $http 请求事例
$http.post(url, data)
    .success(function(result) {
      if(result.ret === 'ok') {
        // success
      } else {
        // error
      }
    })
    .error(function(error) {
      // error
    });

下述封装将判断操作封装起来,不用每次请求都判断:

(function() {
  'use strict';

  angular
    .module('myapp.httpgod', [])
    .factory('HttpGod', HttpGod);

  /**
   * @ngInject
   */
  function HttpGod($http, $q) {
    var httpGod = {};
    var UNKNOW_ERROR = {
      code: -1,
      message: '请求失败'
    };

    var httpSuccess = function(ret, deferred) {
      var retFinal = ret || UNKNOW_ERROR;
      if (retFinal.code !== 0) {
        deferred.reject(retFinal);
      } else {
        deferred.resolve(retFinal);
      }
    };

    var httpError = function(ret, deferred) {
      deferred.reject(ret || UNKNOW_ERROR);
    };

    httpGod.get = function(url, data) {
      var deferred = $q.defer();

      $http.get(url, data)
        .success(function(ret) {
          httpSuccess(ret, deferred);
        })
        .error(function(ret) {
          httpError(ret, deferred);
        });

      return deferred.promise;
    };

    httpGod.post = function(url, data) {
      var deferred = $q.defer();

      $http.post(url, data)
        .success(function(ret) {
          httpSuccess(ret, deferred);
        })
        .error(function(ret) {
          httpError(ret, deferred);
        });

      return deferred.promise;
    };

    httpGod.put = function(url, data) {
      var deferred = $q.defer();

      $http.put(url, data)
        .success(function(ret) {
          httpSuccess(ret, deferred);
        })
        .error(function(ret) {
          httpError(ret, deferred);
        });

      return deferred.promise;
    };

    httpGod.delete = function(url, data) {
      var deferred = $q.defer();

      $http.delete(url, data)
        .success(function(ret) {
          httpSuccess(ret, deferred);
        })
        .error(function(ret) {
          httpError(ret, deferred);
        });

      return deferred.promise;
    };

    httpGod.deferred = function() {
      return $q.defer();
    };

    return httpGod;
  }
})();

如何使用:

  1. 依赖模块 myapp.httpgod
  2. 注入服务 HttpGod
HttpGod.get(url).then(successCb, errorCb);
HttpGod.post(url).then(successCb, errorCb);
HttpGod.put(url).then(successCb, errorCb);
HttpGod.delete(url).then(successCb, errorCb);