当我知道请求在服务器端失败时,我想知道如何模拟promise $http.这是我的代码:
if ( !ng.isString(email) ) { var promise = $q.defer().promise; $q.reject(); return promise; } return $http( { method : "PUT",url : "//localhost/update",data : { data: email } }) // Success handler .success(response){ return response}) // Error handler .error(errorMsg){ return errorMsg});
您可以使用resolve和reject来控制数据流:
假设你有这样的服务:
var app = angular.module("mymodule.services",[]); app.factory("HttpRequest",['$q','$http',function(q,http) { var deferredData = q.defer(); http.get('http://your-server.local/data.json').success(function(data) { //success,resolve your promise here deferredData.resolve(data); }).error(function(err) { //error,use reject here deferredData.reject(err); }); return { get: function() { return deferredData.promise; } }; }]);
然后可以使用该服务:
var app = angular.module("mymodule.controllers",['mymodule.services']); app.controller("MyCtrl",['HttpRequest','$scope',function(res,scope) { //the "then"-method of promises takes two functions as arguments,a success and an erro callback res.get().then(function(data) { //first one is the success callback scope.data = data; },function(err) { scope.err = err; }); }]);
您可以在第二个回调中处理错误.