【发布时间】:2016-09-28 08:40:06
【问题描述】:
用例:
我想创建一个 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 {};
});
};
});
【问题讨论】:
标签: javascript jquery angularjs ajax angularjs-service