如何从Factory Angular返回数据?

时间:2015-04-06 18:57:14

标签: angularjs

如何从工厂返回数据?

.factory('albumService', ['$http', function($http) {

            return {
                getAlbums: function (type) {

                    var request = $http({
                        method: "POST",
                        url: "/albums/getalbums",
                        data: $.param({ type : type }),
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                    });

                    request.success(function (data) {
                        return data;
                    });
                }
            };
        }])

我需要从工厂的

部分返回数据
request.success(function (data) {
      return data;
});

该结果将在$scope.albums = albumService.getAlbums('select');

1 个答案:

答案 0 :(得分:3)

服务:

    .factory('albumService', ['$http', '$q, function($http,$q) {
        return {
            getAlbums: function (type) {
                var albumPromise = $q.defer();
                $http({
                    method: "POST",
                    url: "/albums/getalbums",
                    data: {'type':type},
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                })
                 .success(function(data){
                    return albumPromise.resolve(data);
                  })
                 .error(function(error){
                    return albumPromise.reject(error);
                 })
               return albumPromise.promise;
            }
        };
    }])

Inside yr Controller会像这样调用它。

albumService.getAlbums('select')
       .then(function(data){
           $scope.albums=data; 
        }, function(error){
           console.log('failed'+error);  
        })