用例:
我想在 Angular 中创建一个服务,它将返回一个数据对象,该对象是服务内部的变量,通过 ajax 调用更新一次。
第一次通过ajax没有收到数据时,会返回{}。一旦收到数据,它将始终返回该数据。
问题:
数据在ajax中被正确接收。接收到的数据结构是一个对象。我已经通过登录控制台进行了检查。但是下次调用此服务时,它会再次调用 ajax,因为服务内的变量没有更新。
任何人都可以建议为什么会发生这种情况以及实现上述目标的闲置方法是什么?
代码:
angular.module('myapp', []).service('TagService', function ($http, CONSTANTS) {
this.tagsData = {};
this.getTagsData = function (cacheMode) {
if (JSON.stringify(this.tagsData) != "{}") {
console.log("returning from cache");
return this.tagsData;
}
$http({
method: 'GET',
url: CONSTANTS['base_url_s'] + 'api/v1/get_all_tags_data/',
params: {'params': JSON.stringify({})}
}).success(
function (data, status, headers, config) {
if (data && data["success"] && data["success"] == true) {
this.tagsData = data["data"];
}
return this.tagsData;
}).error(
function (data, status, headers, config) {
return {};
});
};
});
最佳答案
您不应在函数中使用this。 this 关键字是函数作用域的。您没有在回调和第一个条件中更新相同的变量。
angular.module('myapp', []).service('TagService', function ($http, CONSTANTS) {
var tagsData = {};
this.getTagsData = function (cacheMode) {
if (JSON.stringify(tagsData) != "{}") {
console.log("returning from cache");
return tagsData;
}
$http({
method: 'GET',
url: CONSTANTS['base_url_s'] + 'api/v1/get_all_tags_data/',
params: {'params': JSON.stringify({})}
}).success(
function (data, status, headers, config) {
if (data && data["success"] && data["success"] == true) {
tagsData = data["data"];
}
return tagsData;
}).error(
function (data, status, headers, config) {
return {};
});
};
});
还有一件事,您必须使用 promise 而不是返回数据。 Check the documentation about $q here.
正确的方法应该是:
angular.module('myapp', []).service('TagService', function ($http, CONSTANTS, $q) {
var tagsData = {};
this.getTagsData = function (cacheMode) {
var defer = $q.defer();
if (JSON.stringify(tagsData) != "{}") {
console.log("returning from cache");
defer.resolve(tagsData);
}else{
$http({
method: 'GET',
url: CONSTANTS['base_url_s'] + 'api/v1/get_all_tags_data/',
params: {'params': JSON.stringify({})}
}).success(
function (data, status, headers, config) {
if (data && data["success"] && data["success"] == true) {
tagsData = data["data"];
}
return defer.resolve(tagsData);
}).error(
function (data, status, headers, config) {
return defer.reject({});
});
};
}
return defer.promise;
});
然后你应该调用:
TagService.getTagsData().then(function(yourTags){
// yourTags contains your data
});
关于javascript - Angular 服务中的数据对象变量通过ajax调用更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37526980/