简体   繁体   中英

$scope variable is not updating in controller , in successful $http GET request

My code

/* code written for my factory */

/**
*  service/factory
*
* Description
*/

angular
    .module('Translationapp')
    .factory('LogService', LogService);

LogService.$inject = ['$rootScope','$http', '$q', 'API_URL'];

function LogService ($rootScope,$http, $q,appurl) {

    var req = {
            method: 'GET',
            url: appurl+'getlogs',
    }

    var defer = $q.defer();

    var logdata =  {
        getLogs : getLogs,
        AllLogs : []
    }

    return logdata;

    function getLogs () {

        $http.get('http://localhost/welcome_translation/getlogs')
            .then(getLogsComplete)
            .catch(getLogsFailed);

        return defer.promise;      
    }

    function getLogsComplete (response) {

        logdata.AllLogs = response.data;
        console.log('responsedata ='+JSON.stringify(logdata.AllLogs)); // getting data here
        defer.resolve(response);

    }

    function getLogsFailed () {
        defer.reject('Some Error');
    }
}

/* code for my controller */

/*
controller for logs
*/

angular
    .module('Translationapp')
    .controller('LogsController', ['$rootScope','$scope', '$http', 'API_URL','$filter' , 'NgTableParams', 'LogService' , function($rootScope, $scope,$http, appurl,$filter, NgTableParams, LogService){

    $scope.currentindex = 1;

    $scope.logs = LogService.AllLogs;

    logs();

    function logs() {


        /**
        * Step 1
        * Ask the getLogs function for the
        * logs data and wait for the promise
        */

        return getLogs().then(function(response) {

            /**
            * Step 4
            * Perform an action on resolve of final promise
            */
            //console.log(JSON.stringify(response.data));
            $scope.logs = response.data; 
            console.log(JSON.stringify($scope.logs));   // here I am getting the data
            //return $scope.logs;
        });
    }

    console.log('All Log ='+ JSON.stringify($scope.logs)); // getting no data here

    function getLogs() {
      /**
       * Step 2
       * Ask the data service for the data and wait
       * for the promise
       */
      return LogService.getLogs()
        .then(function(data) {

            /**
            * Step 3
            * set the data and resolve the promise
            */
            return data;
        });
    }

    /* get list of roles */

    $http.get(appurl+'getroles')
            .success(function (response) {
                $scope.roles = response;
            });

    $scope.onTimeSet = function (newDate, oldDate) {
        $scope.formattedDate = $filter('date')(newDate, 'dd-MM-yyyy')
    }

    $scope.tableParams = new NgTableParams(
            { 
                page: 1, 
                count: 5,

            },
            {
                total: $scope.logs.length,
                counts: [],
                getData: function($defer, params) {
                $scope.data = $scope.logs.slice((params.page() - 1) * params.count(), params.page() * params.count());
                $defer.resolve($scope.data);
            }
    });

}]);

I extracted the relevant part of your code:

getLogs().then(function(response) {
   $scope.logs = response.data; 
   console.log(JSON.stringify($scope.logs));   // here I am getting the data
});

console.log('All Log ='+ JSON.stringify($scope.logs)); // getting no data here

The problem is that the success handler passed to then is called asynchronously when the logs are eventually retrieved. However, the console.log for which you see no output happens right after the request for the logs has been issued but long before they are retrieved. That's the whole point about promises. You pass a handler to execute once the results are there. But you can immediately do other stuff regardless how long it takes until the promise is fulfilled.

If this is not clear to you I recommend to start with a JS promise tutorial that teaches you the main concepts you need to understand. This post might be helpful:

http://www.html5rocks.com/en/tutorials/es6/promises/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM