0

I try to use a service to get some data from server, but I had a problem: even the console log out the length when I print 'myData.length', when I try to find length of '$scope.test' controller variable it tell me that it is undefined.

What I should to do to use a $http service inside my own service?

app.controller('mainCtrl', ['$scope', 'mapServ',
function($scope, mapServ) {
    $scope.test = [];
    $scope.test = mapServ.test;
    console.log('$scope.test = ' + $scope.test.length);
}]);

app.factory('mapServ', ['$http', function ($http) {
    var path = "file path to my server data";
    var out = {};
    var myData = [];
    out.test = $http.get(path).then(function (response) {
            myData = response.data;
            console.log(myData.length);
    });
    return out;
}]);
Doro
  • 335
  • 2
  • 6
  • 24
  • You don't seem to understand promises. Read http://blog.ninja-squad.com/2015/05/28/angularjs-promises/ – JB Nizet Oct 24 '16 at 11:53
  • Look at my answer on [how can i send ajax requests?](http://stackoverflow.com/questions/40048960/how-can-i-send-requests-to-json/40052067#40052067) – Ajeet Lakhani Oct 24 '16 at 11:57

3 Answers3

1

In your code you do not wait that $http has finished.

$http is an asynchronous call

You should do it like this

app.controller('mainCtrl', ['$scope', 'mapServ',
    function($scope, mapServ) {
        $scope.test = [];
        $scope.test = mapServ.test.then(function(response) {
            console.log(response.data);
        }, function(error) {
            //handle error
        });;
    }
]);

app.factory('mapServ', ['$http', function($http) {
    var path = "file path to my server data";
    var out = {};
    var myData = [];
    out.test = $http.get(path);
    return out;
}]);
Weedoze
  • 13,683
  • 1
  • 33
  • 63
  • I need to read data from my service, because I have to make some calculations (a map with some markers and another facilities) and get only the result (an array of objects). I read about $q deferr but I failed to implement it... – Doro Oct 24 '16 at 11:59
1

Take these service and controller as an example and you should follow John Papa's style guide while writing the code.

Service

(function() {
            'use strict';

            angular
                .module('appName')
                .factory('appAjaxSvc', appAjaxSvc);

            appAjaxSvc.$inject = ['$http', '$q'];

            /* @ngInject */
            function appAjaxSvc($http, $q) {

                return {
                    getData:function (path){

                      //Create a promise using promise library
                        var deferred = $q.defer();

                        $http({
                            method: 'GET', 
                            url: "file path to my server data"
                        }).
                        success(function(data, status, headers,config){
                            deferred.resolve(data);
                        }).
                        error(function(data, status, headers,config){
                            deferred.reject(status);
                        });

                        return deferred.promise;
                    },
                };
            }
        })();

Controller

    (function() {

        angular
            .module('appName')
            .controller('appCtrl', appCtrl);

        appCtrl.$inject = ['$scope', '$stateParams', 'appAjaxSvc'];

        /* @ngInject */
        function appCtrl($scope, $stateParams, appAjaxSvc) {
            var vm = this;
            vm.title = 'appCtrl';

            activate();

            ////////////////

            function activate() {

                appAjaxSvc.getData().then(function(response) {
                    //do something
                }, function(error) {
                    alert(error)
                });

            }
        }
    })();
Ajeet Lakhani
  • 3,768
  • 2
  • 22
  • 37
0

$http call that you are making from factory is asynchronous so it will not wait , until response come, it will move on to the next execution of the script, that is the problem only try Weedoze's asnwer, it is correct way to do this.

Jigar7521
  • 1,549
  • 14
  • 27