Hayot
Hayot

Reputation: 251

How to get data result from service in angular

I have to get the data which comes from API and in this case I used a controller and a service, it's service `daryo.factory('daryoSvc', ['$http', function ($http) {

var categories = [];

var categoriesjon = function () {
    $http.get('http://localhost:18737/Category/GetCategories').
        success(function (data, status, headers, config) {
            categories = {
                "one": "two",
                "key": "value"
            };
            alert('g');
        })
        .error(function (data, status, headers, config) {
            console.error(data);
        });

    return categories;
}

var factoryService = {
    categories: categoriesjon
};

return factoryService;

}]);`

and here is my Controller function `daryo.controller('daryoCtrl', ['$scope', 'daryoSvc', function ($scope, daryoSvc) {

var self = $scope;
self.categories = daryoSvc.categories;

console.log(daryoSvc.categories);

}]);`

It's not working correctly,because I didn't use $q promise options and I didn't find a good solving for that, How can I fix that? Thanks!

Upvotes: 0

Views: 524

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

Your service returns an empty array. This empty array is then replaced by a new one once the asynchronous http call succeeds, but the controller using this service still has a reference to the old, empty array. Another problem is that the controller doesn't even call the service. All it does is store a reference to the service function in the scope.

The code should be

var categoriesjon = function () {
    // executed at t1
    return $http.get('http://localhost:18737/Category/GetCategories').
        then(function (response) {
            // executed at t2, long after t1
            var categories = {
                "one": "two",
                "key": "value"
            };
            return categories;
        })
        .catch(function (response) {
            console.error(response.data);
        });
};

and in the controller:

// executed at t0
daryoSvc.categories().then(function(data) {
    // executed at t3
    $scope.categories = data;
});

Upvotes: 2

Related Questions