0

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!

1 Answer 1

2

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;
});
Sign up to request clarification or add additional context in comments.

6 Comments

it returns undifined which data in controller
Try replacing success() with then() and error() with catch().
What returns undefined? how are you getting that undefined value?
with console.log(self.categories) which I write in controller
I'm using this in controller daryoSvc.categories().then(function (data) { self.categories = data; });
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.