2013-10-14 28 views
0

角度方式如何向用戶顯示視覺反饋,以表明appp正在等待來自服務器的答案?angularjs針對服務器請求的視覺反饋

目前,我有工廠,下面的代碼

app.factory('MyAppFact', ['$http', '$q', 
function($http, $q) { 
    function _success(data, status) { 
     document.body.classList.remove('waitserver') 
     if (data.status == 'OK') { 
      this.resolve(data); 
     } else { 
      this.reject(data); 
     } 
    } 
    function _error(data, status) { 
     document.body.classList.remove('waitserver') 
     this.reject(status})  
    } 
    return { 
     changeLocale: function(locale){ 
      var d = $q.defer(); 
      document.body.classList.add('waitserver'); 
      $http.get('/changeLocale/'+locale).success(_success.bind(d), 
       _error.bind(d)); 
      return d.promise; 
     }, 
     login: function(uname, passwd, keep) { 
      var d = $q.defer(); 
      document.body.classList.add('waitserver'); 
      $http.post('/login', {uname:uname, passwd:passwd, keep:keep} 
       ).success(_success.bind(d), _error.bind(d)); 
      return deferred.promise; 
     }, 
     register: function(user) { 
      var d = $q.defer(); 
      document.body.classList.add('waitserver'); 
      $http.post('/register', {user:user}).success(_success.bind(d), 
       _error.bind(d)); 
      return deferred.promise; 
     }, 

     ... 

    } 
}]); 

儘管此代碼的工作,我加入到文檔正文CSS類,而根據angularjs文檔,我不應該改變DOM在工廠方法中,從而違反了MVC的清晰分離。但是我不明白我在這種情況下如何完成分離。

+0

看看http://stackoverflow.com/questions/18743656/angular-ui-grid-how-to-show-a-loader – Whisher

回答

0

您可以組合一些全局狀態,ng-class指令(應用於<body>或動態角度管理內容的包裝器元素)和描述爲here的HTTP攔截器。

因此,全局狀態就像活動請求計數器一樣,實現爲服務或$rootScope的成員。讓我們考慮爲了簡單起見第二,雖然第一次似乎更正確:

$rootScope.activeRequestsCounter = 0; 

您註冊操縱反攔截:

$provide.factory('myHttpInterceptor', function($rootScope) { 
    function increase() { 
     $rootScope.activeRequestsCounter++; 
    } 

    function decrease() { 
     $rootScope.activeRequestsCounter--; 
    } 

    return { 
     request: increase, 
     requestError: decrease, 
     response: decrease, 
     responseError: decrease 
    }; 
}); 


// in some config block: 
$httpProvider.interceptors.push('myHttpInterceptor'); 

在HTML:

<body ng-class="{waitserver: activeRequestsCounter &gt; 0}"> 

這是操作原理,細節可能需要細化。你獲得的是你不再需要擔心在每個服務調用中添加/刪除類。您可以調用多個服務,並且計數器將正確更新。而且你不會在服務內部操作DOM(更簡潔的代碼)。

+0

謝謝。我會稍微改變一下,但是設置一個$ rootScope變量就可以了 –