Angular Service - 将$ http数据传递给范围

时间:2014-12-10 12:20:38

标签: angularjs http service

我试图在Service上创建一个角度函数,通过$ http返回访问数据,然后返回到所需的范围。

所以我的服务就像这样;

app.service('agrService', function ($http) {

    this.testinho = function(){
        return "teste";
    }

    this.bannerSlides = function(){

        var dataUrl = "data/banner-rotator.json";

        // Simple GET request example :
        $http({
            method: 'GET',
            dataType: "json",
            url: dataUrl
        })
        .success( function(data, status, headers, config) {

            // this callback will be called asynchronously
            // when the response is available

            //console.log(data);
            return data;

        }).error( function(data, status, headers, config) {

            // called asynchronously if an error occurs
            // or server returns response with an error status.
            alert("Niente, Nada, Caput");
        });

    }

})

然后我想将返回的数据关联到我的主App控制器内的范围......就像这样:

app.controller('AppCtrl', function($scope, $http, agrService) {
    $scope.slides = agrService.bannerSlides();
})

然后在我的模板中,我想循环这样的数据:

<div ng-repeat="slide in slides">
    <div class="box" style="background: url('{{ slide.url }}') no-repeat center;"></div>
</div>

问题是数据仅在成功时可用,我不知道如何将其传递给我的示波器幻灯片!!!!!

我做错了什么?

非常感谢提前

4 个答案:

答案 0 :(得分:4)

bannerSlides()不会立即返回您需要的值。它返回一个可以用来在以后获取值的承诺。

在您的服务中,您可以使用.then()生成的承诺的$http()方法来初步处理结果:

 return $http({
    method: 'GET',
    dataType: "json",
    url: dataUrl
 }).then(function (data) {
     // inspect/modify the received data and pass it onward
     return data.data;
 }, function (error) {
     // inspect/modify the data and throw a new error or return data
     throw error;
 });

然后你可以在控制器中执行此操作:

app.controller('AppCtrl', function($scope, $http, agrService) {
     agrService.bannerSlides().then(function (data) {
         $scope.slides = data;
     });
})

答案 1 :(得分:1)

在您的服务中使用此

.... 
this.bannerSlides = function(){
     var dataUrl = "data/banner-rotator.json";
     return $http({
        method: 'GET',
        dataType: "json",
        url: dataUrl
    });
};  
...

这在你的控制器中

agrService.bannerSlides().then(function(data) {
    $scope.slides = data;
}, function() {
   //error
});

您在服务中不需要$q承诺,因为$ http默认返回承诺

  

$ http服务是一个函数,它接受一个参数 - 一个配置对象 - 即       用于生成HTTP请求并使用两个$ http特定方法返回一个promise:成功和错误

reference

这是一个Fiddle Demo

答案 2 :(得分:0)

您需要在回调中返回承诺并更新范围:

app.service('agrService', function ($q, $http) {

 this.bannerSlides = function(){
    var ret = $q.defer();
    var dataUrl = "data/banner-rotator.json";

    // Simple GET request example :
    $http({
        method: 'GET',
        dataType: "json",
        url: dataUrl
    })
    .success( function(data, status, headers, config) {

        // this callback will be called asynchronously
        // when the response is available

        ret.resolve(data);

    }).error( function(data, status, headers, config) {

        // called asynchronously if an error occurs
        // or server returns response with an error status.
        ret.reject("Niente, Nada, Caput");
    });
    return ret.promise;

 }
})

app.controller('AppCtrl', function($scope, $http, agrService) {
 $scope.slides = null;

 agrService.bannerSlides().then(function(data){
   $scope.slides = data;
 }, function(error){
   // do something else
 });

})

答案 3 :(得分:0)

您无法从异步调用返回常规变量,因为在此成功块被执行时,该函数已完成迭代。 您需要返回一个promise对象(作为指导,并优先从服务中执行)。

按照$q$http的角度文档,您可以为自己构建异步调用处理模板。

模板应该是这样的:

angular.module('mymodule').factory('MyAsyncService', function($q, http) {

var service = {
    getData: function() {
        var params ={};
        var deferObject = $q.defer();
        params.nameId = 1;
        $http.get('/data', params).success(function(data) {
            deferObject.resolve(data)
        }).error(function(error) {
            deferObject.reject(error)
        });

        return $q.promise;
    }
}
});

angular.module('mymodule').controller('MyGettingNameCtrl', ['$scope', 'MyAsyncService', function ($scope, MyAsyncService) {

    $scope.getData= function() {
        MyAsyncService.getData().then(function(data) {
            //do something with data
        }, function(error) {
            //Error 
        })
    }
}]);