我在应用程序的多个 Controller 中使用了一项服务。
该服务包含对 PHP 脚本的 $http 调用,该脚本返回一些重要数据。
我想要做的是,如果请求失败,则从用户的localstorage
获取该数据,然后在所有 Controller 中调用与 $http success 绑定(bind)的所有函数。
这就是我的服务的一部分:
app.service('initialJSON', ['$http', function ($http) {
var vm = this;
vm.json = $http.get(url);
vm.json.success(function (data) {
if (typeof Storage !== "undefined") {
localStorage.initialJSON = data;
}
})
vm.json.error(function (data, status) {
if (typeof Storage !== "undefined" && "initialJSON" in localStorage) {
// call all success functions in all controllers with the locally saved data
}
});
}]);
作为示例,应调用此 Controller 中的函数:
app.controller('someCtrl', ['initialJSON', function(initialJSON) {
var vm = this;
initialJSON.json.success(function (data) {
// This function should be called and do some things with the data
});
}]);
我不知道这是否可能,也不知道我需要改变多少结构才能使其成为可能,但如果有人有想法,我将非常感激。
最佳答案
不要让您的 Controller 重复使用相同的 $http promise ,而是创建您自己的 Controller ,一旦获得结果,您将使用结果进行解析。
app.service('initialJSON', ['$http', '$q', function ($http, $q) {
var vm = this;
var deferred = $q.defer();
vm.json = deferred.promise;
var request = $http.get(url);
request.then(function (response) {
if (typeof Storage !== "undefined") {
localStorage.initialJSON = response.data;
deferred.resolve(response.data);
}
})
request.catch(function () {
if (typeof Storage !== "undefined" && "initialJSON" in localStorage) {
deferred.resolve(localStorage.initialJSON);
}
});
}]);
如果您的 Controller 只关心成功,则上述内容应该有效。如果您还需要它们能够处理错误,则需要以某种方式扩展它,以便在两次尝试获取数据后调用 deferred.reject()
。
关于javascript - 如何在 Angular 中模拟 $http 成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40618260/