Angular Service - Passing $ http data to scope

I am trying to create an angular function inside a service to return acess data via $ http and then return to the desired scope.

So my service is something like this;

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");
        });

    }

})

      

Then I want to bind the returned data to a scope inside my main app controller ... for example:

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

      

Then in my template, I want to encode the data like this:

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

      

The problem is that the data is only available for success and I don't know how to pass it to my slides. !!!

What am I doing wrong?

Thank you very much in advance

+3


source to share


4 answers


bannerSlides()

doesn't return the values ​​you want. It returns a promise that you can use to retrieve the value at a later time.

In your service, you can use the .then()

promise method , which it $http()

creates for initial processing of the result:

 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;
 });

      



and then you can do this in your controller:

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

      

+3


source


Use this in your service

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

      

And this is in your controller

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

      



you don't need a $q

promise inside the service because $ http returns a default promise

The $ http service is a function that takes one argument - a config object - this file is used to generate an HTTP request and returns a promise with two special $ http methods: success and error

link

here Fiddle Demo

+1


source


You need to return the promise and update the scope in the callback:

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
 });

})

      

0


source


You cannot return a regular variable from an asynchronous call because by the time this block of success completes, the function has already completed its iteration. You need to return the promise object (as a path string and use it from the service).

By following the angular doc for $ q and $ http you can create your own template to handle asynchronous calls.

The template should be something like this:

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 
        })
    }
}]);

      

0


source







All Articles