2014-09-13 3 views
1

Я пытаюсь присвоить свойство объекта услуги с помощью $http, но у меня запутанные результаты. Почему это не работает (вот мой код):присвоить значение свойства услуги (Angularjs)

.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 

ответ

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

Вы можете прочитать больше о том, что:

+0

Большое спасибо, я узнаю об этом :) – navotera

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

я попробовать ваше предложение, но то, что делает меня запутать в данный момент: 'вар онлайн = config.online.then (функция (данные) { data.response; // это предупреждение работает //alert(data.response); }); // это предупреждение не работает (объект возврата) alert (онлайн); ' – navotera

+0

извините, я не могу проголосовать за вас, мой представитель> 15 , но спасибо в любом случае – navotera

Смежные вопросы