1. 程式人生 > >前端開發框架總結之Angular實用技巧(四)

前端開發框架總結之Angular實用技巧(四)

                       前端開發框架總結之Angular實用技巧(四)

上文講了Angular中路由的相關的知識,掌握了這些,我們就可以構建比較複雜的頁面結構和UI互動了。今天我們再來介紹下angular $http請求相關的知識。

  • angular網路請求

angular的網路請求方式在不同的版本是不一樣的,但方式大差不差。直接上程式碼,大家參考這個方式寫就行了。

    function doAuth() {
        $http({
            method: 'POST',
            headers:{'Content-Type':'application/json-rpc'},
            url: Constants.zabbixUrl,
            data: JSON.stringify(reqObj),
        }).success(function(data,status,headers,config){
            if(data.result){
                Constants.zabbixAuth = data.result;
            }
        }).error(function(data,status,headers,config){
        });
    };

我們常用的引數也就這幾項。

method:請求方式,包括post get等

headers:請求頭資訊。

url:請求路徑

data:包體中攜帶的資料。

params:區別於data,這個是get型別的引數,預設的會用$httpParamSerializer進行序列化。

transformRequest:請求資料的頭部和包體的“攔截器”,攔截的第一個引數對應的是data所攜帶的資料,可以對這個資料進行序列化。

在springmvc框架中使用angular的話,前端資料如果是一個物件,如果想要在後臺do方法中做到正確的對映,可以把物件放在params中,也可以把物件放在data中,但是要通過transformRequest進行序列化。

另外springmvc中前臺請求的頭部資訊中Content-Type是需要配置成'application/x-www-form-urlencoded;charset=utf-8'的,不能配置成json格式的,否則會造成後臺無法接收到資料。

 

請求成功返回會進入success的回撥。失敗會進入error的回撥。$http返回的是一個promise。

$http請求頭的預設配置方式:

  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
  $httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript, */*; q=0.01';

$http請求的攔截方式:

  $httpProvider.interceptors.push(['$rootScope', '$q','$timeout','$cookies','Constants', function ($rootScope, $q, $timeout,$cookies,Constants) {
    return {
      'request': function (config) {
        config.headers['X-Requested-With'] = 'XMLHttpRequest';
        config.timeout = 30000;
        config.cache = false;

        if (config.url.search(/log-service-idgen\*/) >= 0) {
            return config || $q.when(config);
        }

        if (config.method == "POST") {
            config.headers['USER'] = $cookies.get('account');
            config.headers['TOKEN'] = $cookies.get('token');

            if (config.url.search(/\?/) >= 0) {
                config.url = config.url + "&ver=" + new Date().getTime();
            } else {
                config.url = config.url + "?ver=" + new Date().getTime();
            }
        } else if (config.method == "GET") {
          if (config.url.search(/\?/) >= 0) {
            config.url = config.url + "&ver=" + new Date().getTime();
          } else {
            config.url = config.url + "?ver=" + new Date().getTime();
          }
        }
        return config || $q.when(config);
      },
      'requestError': function (rejection) {
        return rejection;
      },
      'response': function (response) {
        if (response.headers().sessionstatus == "timeout") {

          return {
            data: {
              result: false,
              message: {
                errCode: '401',
                errDesc: "登入超時,請重新登入!"
              }
            }
          };
        } else {
          return response || $q.when(response);
        }

      },
      'responseError': function (response) {
        if (response.status === 401) {
          $rootScope.alertObj = {
            isShow: true,
            text: "未授權,請先登入!",
            fun: function () {
              $rootScope.loginUser = {};
              $rootScope.changeState('login', {actionType: 1});
            }
          };
          return false;
        } else if (response.status === 404) {
          $rootScope.alertObj = {
            isShow: true,
            text: "訪問的地址不存在!",
            fun: function () {
            }
          };
          return false;

        } else if (response.status === 500) {
          $rootScope.alertObj = {
            isShow: true,
            text: "伺服器內部異常!",
            fun: function () {
            }
          };
          return false;
        } else if (response.status === 504) {
          $rootScope.alertObj = {
            isShow: true,
            text: "連線服務超時,請稍後重試!",
            fun: function () {
            }
          };
          return $q.reject(response);
        } else {
          $rootScope.alertObj = {
            isShow: true,
            text: response.statusText ? response.statusText : "網路異常!",
            fun: function () {
            }
          };
          return false;
        }
        return $q.reject(response);
      }
    };
  }]);

另外說明一點,angular的$http是非同步的,沒有想jquery中還提供了了同步的配置方式。

有一篇文章對$http引數介紹挺詳細的:https://blog.csdn.net/Candy_home/article/details/47114157