javascript - 分配服务属性的值(Angularjs)

标签 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

在我的 Controller 中:

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

最佳答案

服务:

.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

Controller :

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
});

关于javascript - 分配服务属性的值(Angularjs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25828339/

相关文章:

javascript - 使用 jquery 获取下拉列表的 json 数据不起作用

javascript - 带有谷歌地图的AWS服务器

javascript - Angular Testing - promise 不返回数据

javascript - AngularJS 和 Typescript - 注入(inject)服务

javascript - 如何在语义 ui 数据表中对齐页面长度、导出按钮和搜索栏?

javascript - googlechart 可以同时查询超过 1 个电子表格吗?

javascript - 多次触发全局混合 - Vue

angularjs - 在 Visual Studio 中调试 AngularJS(不是在 VS Code 中)

javascript - Angular : Service variable changes not applying

javascript - 如何在 angularjs 中将数据从工厂传递到我的 Controller ?