Peter Vögeli
Peter Vögeli

Reputation: 51

angularjs and $http request

Hello I'm new to AngularJs and trying to get json Data from my server. When the service gets executed, I see a clear response in Fiddler. But the success or the error function does not get executed, and so the service returns an empty array.

var app = angular.module('imageApp', []);

app.service('imageService', function ($http) {
    var imageModels = [];
    this.Images = function (url) {
        $http({ method: 'GET', url: url }).success(function (data) {
            imageModels = data;
        }).error(function (data) {
            imageModels = data || "Request failed";
        });

        return imageModels;
        };
    };
});

app.controller('ImageController', function (imageService, $scope) {
    $scope.fetch = function (url) {

        $scope.url = url;
        $scope.ImageModels = imageService.Images($scope.url);
    };
});

Upvotes: 2

Views: 5377

Answers (2)

jofftiquez
jofftiquez

Reputation: 7708

Update your service like this.

app.service('imageService', function ($http, $q) {
    this.Images = function (url) {
        return $http({ method: 'GET', url: url }).success(function (data) {
            $q.resolve(data);
        }).error(function (data) {
            $q.reject(data || "Request failed");
        });
    };
});

Then your controller, you can now wait for a promise to be returned from the service.

imageService.Images($scope.url)
    .then(function(response){
        // success
    }).catch(function(error){
        // error
    })

So what happened? On your service, notice that we added $q to create a promise so we can reslove and reject the response from $http and make it "thenable" on the controller.

Writing a service to handle $http request is always a hassle for me, so I created this angular module to handle things for me. If you want you can check it out.

Upvotes: 0

Mark Rajcok
Mark Rajcok

Reputation: 364677

$http returns results asynchronously. So, return imageModels will execute before the success() or error() callbacks have had a chance to run. You need to wait for the promise that $http creates to resolve -- use then() in your controller.

Rather than repeat it here, see the solution from @Pete BD: https://stackoverflow.com/a/12513509/215945

Upvotes: 2

Related Questions