如何处理Ionic中的$ http承诺

时间:2015-09-12 18:12:44

标签: javascript angularjs ionic-framework promise ionic

我开始使用Ionic,我在使用此代码填充下面的列表时遇到问题。 我认为当promise将列表返回到范围时,屏幕已经开始加载,因此屏幕上没有显示任何内容。 根据我的理解,.then()中实现的任何内容仅在promise返回数据后发生。 通过chrome调试器调试时,$ scope.clients永远不会收到数据。 在这种方法中我应该更改什么才能正确加载列表? 可能是因为我在控制器的主体中调用了.getClients吗? 关于我的方法有什么问题的任何提示都非常感谢。

.factory('ClientFactory', function($http){
  //restful api
  var urlBase = "http://localhost:8080/client";
  return{
    all: function(){
      return [
          { name: 'Client 1', id: 1 },
          { name: 'Client 2', id: 2 },
          { name: 'Client 3', id: 3 },
          { name: 'Client 4', id: 4 },
          { name: 'Client 5', id: 5 }
      ];
    },
    getClients: function(){

      var listaClientes = $http.get(urlBase).
        then(function(response, listaClientes) {
          var x = 'feitoooo';
          console.log(response.data);
          listaClientes = response.data;
          return listaClientes;
        // this callback will be called asynchronously
        // when the response is available
        }, function(response) {
          listaClientes = 'void';
          //return listaClientes;
          // called asynchronously if an error occurs
        // or server returns response with an error status.
      });


    }
  }

})


.controller('ClientCtrl', function($scope, $http, ClientFactory, $timeout, $ionicModal) {

  $scope.clients = ClientFactory.getClients();

  $scope.newClient = function(){ 
     console.log('newClient chamada!!');      

     $scope.clientData = {};

      // Create the login modal that we will use later
      $ionicModal.fromTemplateUrl('templates/client-add.html', {
        scope: $scope
      }).then(function(modal) {
        $scope.modal = modal;
        $scope.modal.show();
  });

      // Triggered in the login modal to close it


}


<ion-view view-title="Client">
  <ion-content>
    <h1>Client control</h1>

    <div class="buttons">
      <button class="button button-icon ion-plus" ng-click="newClient()"></button>
    </div>

    <ion-list>
      <ion-item ng-repeat="client in clients" href="">
        {{client.name}}
      </ion-item>
    </ion-list>

  </ion-content>
</ion-view>

0 个答案:

没有答案