分配服务属性的值(Angularjs)

时间:2014-09-13 22:29:19

标签: javascript angularjs angularjs-service

我尝试使用$http分配服务对象的属性,但结果令人困惑。为什么这不起作用(这是我的代码):

.service('config', function ($http) {
    var config = {
        get_host: function () {
            if (online == 0) {
                return offlineHost;
            }
            return onlineHost;
        },
        online: 'false',
        host: 'false',
        checkConnection: function () {

            //this wont work;
            /* 
            $http.get(this.host + http_url ).then(function(response) { 
                return  response.data.ping;
            });
            */

            //this will work 
            return 'oke';
        },

        _load: function () {
            this.host = this.get_host();
            this.online = this.checkConnection();
            this.url_api = this.host + http_url;

            if (this.online == 1) {
                this.offline_message = 'Maaf aplikasi tidak bisa terkoneksi dengan server atau anda offline';
            }
        }
    };

    //run constructor and get value;
    config._load();

    return config;

}) //end config class

在我的控制器中:

var online = config.online;
alert(online) //return undefined, but the $http request on firebug is showed return value

2 个答案:

答案 0 :(得分:1)

服务:

.service('config', function ($http, $q) {
var config = {
    get_host: function () {
        if (online == 0) {
            return offlineHost;
        }
        return onlineHost;
    },
    online: 'false',
    host: 'false',
    checkConnection: function () {
        var deferred = $q.defer();

        $http.get(this.host + http_url ).then(function(response) { 
            $q.resolve(response.data.ping);
        });

        return $q.promise;
    },

    _load: function () {
        this.host = this.get_host();
        this.online = this.checkConnection();
        this.url_api = this.host + http_url;

        if (this.online == 1) {
            this.offline_message = 'Maaf aplikasi tidak bisa terkoneksi dengan server atau anda offline';
        }
    }
};

//run constructor and get value;
config._load();

return config;

}) //end config class

控制器:

config.online.then(function(data){
    alert(data);
    var online = data;
    handleDate(online); // this is a predefined function to handle your data when it's downloaded
});

答案 1 :(得分:0)

那是因为$http服务调用是异步的。

处理此问题的最简单方法是让您的服务返回承诺:

return $http.get(this.host + http_url);

return前面$http至关重要)。然后代码中的任何地方:

config.checkConnection().then(function(response) { 
    // there you get the response.data.ping
});

请在此处查看修改后的简化代码:http://plnkr.co/edit/cCHXCLCG3xJUwAPPlJ3x?p=preview

您可以阅读更多相关内容: