【问题标题】:Data object variable in angular service to update via ajax call角度服务中的数据对象变量通过 ajax 调用更新
【发布时间】: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


    【解决方案1】:

    您不应在函数中使用 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
    });
    

    【讨论】:

    • 感谢您这么好的回复..真的很感激!!
    • 您的解决方案运行良好,但对于 if (JSON.stringify(this.tagsData) != "{}") { console.log("returning from cache");返回 defer.resolve(tagsData);它不工作....它说未定义的功能 TagService.getTagsData
    • 第一次直到 data 是 {} 它调用 ajax 返回 promise 效果很好,但是之后当它再次被调用并且应该直接返回数据时它会抛出错误:TagService.getTagsData(. ..) 未定义
    • 您好,您还应该在测试中去掉tagsData前面的“this”关键字,去掉“return”部分。我更新了上面的解决方案。抱歉,我错过了这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    相关资源
    最近更新 更多