Doro Doro - 1 month ago 8
AngularJS Question

Using $http inside my own service - variable does not persist

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

Answer

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

            }
        }
    })();