2014-02-07 57 views
2

所以我有一個服務定義如下:

angular.module('services', ['ngResource']) 
    .factory('Things', function ($rootScope, $http) { 
    var basePath = 'rest/things/'; 
    return { 
     getAll: function() { 
      return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {}); 
     } 
    }; 
}); 

然後,在其他地方,我認爲消費服務W /:

Things.getAll().success(function(things){ 
    //do something w/ things 
}) 
.error(function(err){ 
    // Clearly, something went wrong w/ the request 
}); 

我想什麼做的,是能夠例如,如果服務級別的數據存在問題,則「拋出」錯誤條件。即:

數據回來爲:

{ 
    status:500, 
    message:'There was a problem w/ the data for this client' 
} 

因此然後在那裏的服務會是這樣的:

getAll: function() { 
     return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {}) 
    .throwError(function(data){ 
    return (data.status && data.status == 200); 
    }); 
} 

所以當throwError回調返回false,誤差()的承諾然後會被稱爲而不是成功的承諾。

有沒有人有關於如何做到這一點的任何想法?

非常感謝!

+1

創建您服務延遲。實際上,鉤入'$ http'調用的**成功**和**錯誤**回調。在** success **裏面,檢查響應的'status'屬性;如果它不在'200'範圍內,**拒絕**延期。否則,**解決**延期。 **拒絕** **錯誤**回調中的任何內容。並從服務方法 – Ian

+0

返回延期的**許諾**伊恩,謝謝..你能給出一個代碼示例作爲答案嗎? 另外,我應該爲此使用攔截器嗎? http://docs.angularjs.org/api/ng.$http – RavenHursT

+1

如果你確定所有的請求都遵循這個約定,那麼使用攔截器肯定更有意義。你可以像在這個頁面的例子中那樣創建攔截器,並且在'response'回調中,檢查響應的屬性'status'和它是否'bad',使用'$ q.reject(response);'否則返回響應|| $ q.when(response);' – Ian

回答

4

如果您確定所有請求都遵循約定,其中響應返回的數據包含狀態代碼,那麼使用HTTP Interceptor是有意義的。要做到這一點,你可以創建一個服務,並將它推到攔截列表中$httpProvider

.factory("myHttpInterceptor", function ($q) { 
    return { 
     response: function (response) { 
      if (response.data.status && (response.data.status === 500)) { 
       return $q.reject(response); 
      } 
      return response || $q.when(response); 
     } 
    }; 
}); 

您可以用類似>= 400更換=== 500來處理所有的錯誤,不只是一個500

而且裏面你的模塊.config(),補充一點:

$httpProvider.interceptors.push("myHttpInterceptor"); 

參考文獻:

+1

太棒了。謝謝伊恩! – RavenHursT