service不会以角度方式将数据返回给控制器

时间:2016-03-26 13:22:36

标签: javascript angularjs json angular-services

这是我的服务:

app.service('trackService', ['$http', function($http) {
    var data;
    this.topTracks = function(limit) {
        $http({
            method: 'GET',
            url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
            params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
        }).success(function(result) {
            this.data = result.tracks; console.log(this.data); return this.data;
        }); 
    }
}]);

和控制器 -

app.controller('artistSongsCtrl', ['$scope', 'trackService', function($scope, trackService) {
    $scope.data = trackService.topTracks(10);
    //console.log($scope.data);
}]);

如何使用自定义服务中的$ http服务将数据发送到控制器?

2 个答案:

答案 0 :(得分:3)

$http有几个问题是异步的,您的服务方法topTracks()不会返回任何内容。此外,您无法返回success内,无处可返回...使用then()代替

您需要从服务返回承诺,并在控制器

中的承诺回调中设置范围
app.service('trackService', ['$http',
  function($http) {
    var data;
    var self = this;
    this.topTracks = function(limit) {
      return $http({
        method: 'GET',
        url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
        params: {
          api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf',
          format: 'json',
          limit: limit
        }
      }).then(function(result) {
        self.data = result.data.tracks;
        console.log(self.data);
        return self.data;
      });
    }
  }
]);

app.controller('artistSongsCtrl', ['$scope', 'trackService',
  function($scope, trackService) {
    trackService.topTracks(10).then(function(data) {
      $scope.data = data;
      //console.log($scope.data);
    });

  }
]);

答案 1 :(得分:2)

在您的服务中,您正在进行异步GET请求。为了让控制器捕获该响应,您需要返回一个promise。以下是使用$ q的示例:

app.service('trackService', ['$http', '$q', function($http, $q) {
    var data;
    this.topTracks = function(limit) {
        var d = $q.defer();
        $http({
            method: 'GET',
            url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
            params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
        }).success(function(result) {
            this.data = result.tracks; 
            console.log(this.data); 
            d.resolve(this.data);
        }); 
     return d.promise;
    }
}]);