gpt4 book ai didi

angularjs - 如何模拟一个 Angular $http 调用并返回一个行为类似于 $http 的 promise 对象

转载 作者:行者123 更新时间:2023-12-03 12:42:17 25 4
gpt4 key购买 nike

有没有办法返回一个 HttpPromise(或类似的东西)来模拟对 $http 的调用? ?我想设置一个全局变量来指示是否发出了真正的 HTTP 请求,或者是否返回了带有假数据的假 HttpPromise 对象。

例如,我有一个与此类似的服务:

angular
.module('myservice')
.factory('MyService', ['$http', function($http) {
return {
get : function(itemId) {
if (isInTestingMode) {
// return a promise obj that returns success and fake data
}
return $http.get("/myapp/items/" + itemId);
}
};
} ]);

在我的 Controller 中,我调用了与上述类似的服务:
        // Somewhere in my controller

MyService.get($scope.itemId)
.success(function(data) {
$scope.item = data;
})
.error(function(data, status, headers, config) {
$scope.notFound = true;
});

我正在尝试 不是 更改 Controller 代码;我想要 successerror在我的“isInTestMode”中链接仍然有效。
是否可以伪造 HttpPromise以我在服务中描述的方式?

以下是上述“MyService”的修订版(片段),其中包含 successerror在 promise 对象上。但是,我该如何执行 success方法?
        return {
get : function(itemId) {
if (isInTestingMode) {
var promise = $.defer().promise;
// Mimicking $http.get's success
promise.success = function(fn) {
promise.then(function() {
fn({ itemId : "123", name : "ItemName"}, 200, {}, {});
});
return promise;
};
// Mimicking $http.get's error
promise.error = function(fn) {
promise.then(null, function(response) {
fn("Error", 404, {}, {});
});
return promise;
};
return promise;
}
return $http.get("/myapp/items/" + itemId);
}
}

最佳答案

只需使用 deferred $q 的方法服务

    var fakeHttpCall = function(isSuccessful) {

var deferred = $q.defer()

if (isSuccessful === true) {
deferred.resolve("Successfully resolved the fake $http call")
}
else {
deferred.reject("Oh no! Something went terribly wrong in your fake $http call")
}

return deferred.promise
}
然后你可以像 $http 一样调用你的函数 promise (当然,您必须自定义要放入其中的任何内容)。
    fakeHttpCall(true).then(
function (data) {
// success callback
console.log(data)
},
function (err) {
// error callback
console.log(err)
})

关于angularjs - 如何模拟一个 Angular $http 调用并返回一个行为类似于 $http 的 promise 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24390261/

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