Processing $http response in service

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

    Let it be simple. It's as simple as

    1. Return promise in your service(no need to use then in service)
    2. Use then in your controller

    Demo. http://plnkr.co/edit/cbdG5p?p=preview

    var app = angular.module('plunker', []);
    
    app.factory('myService', function($http) {
      return {
        async: function() {
          return $http.get('test.json');  //1. this returns promise
        }
      };
    });
    
    app.controller('MainCtrl', function( myService,$scope) {
      myService.async().then(function(d) { //2. so you can use .then()
        $scope.data = d;
      });
    });
    

提交回复
热议问题