0

I have a project build in AngularJS and I make a http get request to an api that respond with an array.

The problem is that in the response I have a promise and not the array I need.
If I try to assign it to a scope it is undefined.

This is the factory code:

angular.module('app')

.factory('utils', function($rootScope, $translate, $state, $sce, $http) {
    return {
        settings: {},
        getLanguages: function(){

            var _url = $rootScope.baseUrl+'/languages';
            var lang = $http({
                withCredentials: false,
                url: _url,
                method: "GET",
                headers: { 'Content-Type': undefined },
                transformRequest: angular.identity
            });

            return lang;
        }
    };
});

This is the directive code:

angular.module('app').directive('leftPanel', function($rootScope, player, search, users, utils) {
    return {
        restrict: 'E',
        templateUrl: 'assets/views/directives/left-panel.html',
        replace: true,
        scope: true,
        link: function($scope, el) {
            var searchBar = el.find('input');

            $scope.player = player;
            $scope.search = search;
            $scope.users  = users;

            utils.getLanguages().then(
                function(answer){
                    $scope.languages = answer.data;
                }
            );

            console.log($scope.languages);

            searchBar.on('focus', function() {
                if (search.query || search.results.length) {
                    search.showPanel();
                }
            });

            if ($rootScope.isPhone) {
                $rootScope.$on('$stateChangeStart', function() {
                    el.addClass('closed');
                });
            }
        }
    };
});

The problem is in

utils.getLanguages().then(
                function(answer){
                    $scope.languages = answer.data;
                }
            );

            console.log($scope.languages);

I get undefined

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
Christian Giupponi
  • 7,408
  • 11
  • 68
  • 113

1 Answers1

0

I think it will console.log($scope.language) show you undefined. This is because, utils.getLanguages() is async call and control is immediately transferred to further. If you add $timeout for 1 sec, you may get laguages in scope variable.

prashant
  • 127
  • 2
  • 10