gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:59:12 25 4
gpt4 key购买 nike

我尝试使用 $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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com