angularjs - How to fail a successful Angular JS $http.get() promise -
how reject or fail successful $http.get() promise? when receive data, run validator against , if data doesn't have required properties want reject request. know can after promise resolved, seems idea intercept errors possible. i'm familiar benefits of $q, want continue using $http.
you can reject promise returning $q.reject("reason")
next chained .then
.
same $http
, returns promise - follows:
return $http.get("data.json").then(function(response){ if (response.data === "something don't like") { return $q.reject("bad data"); } return response.data; }
this done within service, pre-handles response .then
specified above, , returns data - or rejection.
if want @ app-level, use $http interceptors - service provides functions handle $http requests , responses, , allows intercept response , return either response - same or modified - or promise of response, including rejection.
.factory("foointerceptor", function($q){ return { response: function(response){ if (response.data === "something don't like") { return $q.reject("bad data"); } return response; } } });
same idea above - except, @ different level.
note, register interceptor, need within .config
:
$httpprovider.interceptors.push("foointerceptor");
Comments
Post a Comment