如何实现从路由解析中触发$ http的离子刷新器

时间:2016-02-01 13:12:06

标签: angularjs mobile ionic-framework

我正在开发一个Ionic项目,我正在通过$ http服务从REST API获取数据。我在一个路径中解决这个问题,这个路径带来了服务的承诺,并注入到控制器中。我的doRefresh函数在该控制器内,但是,解析是在路径内,这可能是怀疑。

我的路线就在这里:

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
  .state('home', {
    url: '/',
    templateUrl: 'templates/home.html',
    controller: 'MainCtrl as vm',
    resolve: {
      weather: function(MyService) {
         return MyService.getData();
     }
  });

$urlRouterProvider.otherwise('/');
});

我的服务就在这里

.factory('MyService', function($http) {
   function getData() {
       return $http.get('http://something.api?format=json')
              .then(function(res) {
                 return res.data;
              });
   }

   return {
     getData: getData()
   };
});

最后,这是我的控制器

.controller('MainCtrl', function(weather, $ionicLoading) {

   var vm = this;
   vm.weather = weather;

   vm.doRefresh = function() {
       // how can I resolve the promise here?? It is right? Is this the correct architecture?
   }

});

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

好吧,weather应该返回一个承诺。所以,你可以在你的控制器中这样做:

vm.weather.then(function(){
   ...
})