Processing $http response in service

后端 未结 12 1829
半阙折子戏
半阙折子戏 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:11

    tosh shimayama have a solution but you can simplify a lot if you use the fact that $http returns promises and that promises can return a value:

    app.factory('myService', function($http, $q) {
      myService.async = function() {
        return $http.get('test.json')
        .then(function (response) {
          var data = reponse.data;
          console.log(data);
          return data;
        });
      };
    
      return myService;
    });
    
    app.controller('MainCtrl', function( myService,$scope) {
      $scope.asyncData = myService.async();
      $scope.$watch('asyncData', function(asyncData) {
        if(angular.isDefined(asyncData)) {
          // Do something with the returned data, angular handle promises fine, you don't have to reassign the value to the scope if you just want to use it with angular directives
        }
      });
    
    });
    

    A little demonstration in coffeescript: http://plunker.no.de/edit/ksnErx?live=preview

    Your plunker updated with my method: http://plnkr.co/edit/mwSZGK?p=preview

提交回复
热议问题