gpt4 book ai didi

AngularJS Promises - 模拟 http promise

转载 作者:行者123 更新时间:2023-12-04 10:08:01 24 4
gpt4 key购买 nike

我想知道当我知道请求将在服务器端失败时如何模拟 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;
});
}]);

您可以在第二个回调中处理错误。

关于AngularJS Promises - 模拟 http promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com