Processing $http response in service

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

    I had the same problem, but when I was surfing on the internet I understood that $http return back by default a promise, then I could use it with "then" after return the "data". look at the code:

     app.service('myService', function($http) {
           this.getData = function(){
             var myResponseData = $http.get('test.json').then(function (response) {
                console.log(response);.
                return response.data;
              });
             return myResponseData;
    
           }
    });    
     app.controller('MainCtrl', function( myService, $scope) {
          // Call the getData and set the response "data" in your scope.  
          myService.getData.then(function(myReponseData) {
            $scope.data = myReponseData;
          });
     });
    

提交回复
热议问题