Search code examples
javascriptangularjsangularjs-service

assign value of service property (Angularjs)


I try to assign a property of a service object by using the $http but I have confusing results. Why this doesn't work (here is my code):

.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

In my controller :

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

Solution

  • That's because the $http service calls are asynchronous.

    The easiest way to handle this is to make your service return a promise:

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

    (return in front of $http is crucial here). Then anywhere in the code:

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

    See your modified and simplified code here: http://plnkr.co/edit/cCHXCLCG3xJUwAPPlJ3x?p=preview

    You can read more about that: