Processing $http response in service

后端 未结 12 1836
半阙折子戏
半阙折子戏 2020-11-22 03:36

I recently posted a detailed description of the issue I am facing here at SO. As I couldn\'t send an actual $http request, I used timeout to simulate asynchrono

12条回答
  •  不知归路
    2020-11-22 04:38

    Because it is asynchronous, the $scope is getting the data before the ajax call is complete.

    You could use $q in your service to create promise and give it back to controller, and controller obtain the result within then() call against promise.

    In your service,

    app.factory('myService', function($http, $q) {
      var deffered = $q.defer();
      var data = [];  
      var myService = {};
    
      myService.async = function() {
        $http.get('test.json')
        .success(function (d) {
          data = d;
          console.log(d);
          deffered.resolve();
        });
        return deffered.promise;
      };
      myService.data = function() { return data; };
    
      return myService;
    });
    

    Then, in your controller:

    app.controller('MainCtrl', function( myService,$scope) {
      myService.async().then(function() {
        $scope.data = myService.data();
      });
    });
    

提交回复
热议问题