2014-07-25 7 views
4

아마도이 질문은 이미 물어 보았습니다 만, 아무런 성공도없이 내 오후의 대부분을 검색하고 시도했기 때문에 누군가가 나를 도와 줄 수 있기를 바랍니다.각도 : 몇 초마다 데이터 업데이트

몇 초마다 공장 서비스에서 설정 한 $ http.get() 데이터를 업데이트하고 싶습니다.

나는 내 코드에 몇 가지 의견을 추가했으며 내가 뭘 시도했는지 볼 수있는 몇 가지 오래된 것들을 남겼다. 에,

ovwid.factory('recentClients', [ 
    '$http', 
    '$rootScope', 
function ($http, $rootScope) { 

    var apiURL = '/plugins/data/get_client.php'; 
    var promise; 

    var recentClients = 
    { 
     async: function() 
     { 
      if (!promise) 
      { 
       // $http returns a promise, which has a 'then' function, which also returns a promise 
       promise = 
       $http.get(apiURL) 
        .then(function (response) { 
        // The then function here is an opportunity to modify the response 
        // The return value gets picked up by the then in the controller. 
        return response.data; 
       }); 
      } 
      // Return a promise to the controller 
      return promise; 
     } 
    } 
    return recentClients; 
}]); 


ovwid.controller(‘client’Ctrl, [ 
    '$scope', 
    'recentClients', 
    '$interval', 
function ($scope, recentClients, $interval) { 

    $scope.loading = true; 

    function reloadData() { 
     // a call to the async method 
     recentClients().async().then(function(data) { 
      // console.log(data); 
      $scope.loading = false; 
      $scope.client = data; 
     }); 
    } 

    // Initizialize function 
    reloadData(); 

    // Start Interval 
    var timerData = 
    $interval(function() { 
     reloadData(); 
    }, 1000); 

    // function myIntervalFunction() { 
    //  var cancelRefresh = $timeout(function myFunction() { 
    //   reloadData(); 
    //   console.log('data refres') 
    //   cancelRefresh = $timeout(myFunction, 5000); 
    //  },5000); 
    // }; 

    // myIntervalFunction(); 

    // $scope.$on('$destroy', function(e) { 
    //   $timeout.cancel(cancelRefresh); 
    // }); 
}]); // [/controller] 

답변

1

몇 가지 문제가 있습니다.

첫째 :

if (!promise)는 처음에만 true를 반환하는 것입니다. 이 번호를 $http 호출에 지정합니다.

둘째 :

당신은 당신의 공장에서 async 방법에 액세스하지 않습니다. return recentClients.async 공장에서 반환하거나 범위에서 호출해야합니다. recentClients.async().then(..

+0

답장을 보내 주셔서 감사합니다. 'recentClients.async()를 호출하고 있습니다. –

+0

질문 : – charlietfl

+0

당신의 관찰 덕분에'! promise'를 제거하여 해결했습니다 –

1

이 될 수는

function reloadData() { 
     // a call to the async method 
     $scope.loading = true; 
     recentClients().then(function(data) { 
      // console.log(data); 
      $scope.loading = false; 
      $scope.client = data; 
     }); 
    } 


// Start Interval 
var timerData = 
$interval(function() { 
    if(!$scope.loading){ 
     reloadData(); 
    } 

}, 1000); 
1

몇 가지 :

recentClients().then(function(data)... 작동하지 않습니다 도움이 될 것입니다 : 내 코드가

(오래된 물건도 주석) 현재 코드는 다음과 같아야합니다 : recentClients.async().then(function(data)

매우 까다로울 수있는 qoutes에 `을 입력하십시오.


내가 설계 서비스에 사용하는 구문입니다

ovwid.factory('recentClients', ['$http', '$rootScope', function ($http, $rootScope) { 
    var apiURL = 'aaa.api'; 

    var recentClients = function() { 
     return $http.get(apiURL) 
    } 

    return { 
     recentClients : recentClients 
    }; 
    }]); 

전체 예 :

(단, 일부 더미 데이터 aaa.api 파일을 만들 서버를 발사하고 데이터가 변경되는 것을 볼 수 있습니다)

<!DOCTYPE html> 
<html> 
<head> 
    <title>Sorting stuff</title> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> 

    <script> 
    var ovwid = angular.module("ovwid", []); 

    ovwid.factory('recentClients', ['$http', '$rootScope', function ($http, $rootScope) { 
    var apiURL = 'aaa.api'; 

    var recentClients = function() { 
     return $http.get(apiURL) 
    } 

    return { 
     recentClients : recentClients 
    }; 
    }]); 


ovwid.controller('clientCtrl', [ 
    '$scope', 
    'recentClients', 
    '$interval', 
function ($scope, recentClients, $interval) { 

    $scope.loading = true; 

    function reloadData() { 
     // a call to the async method 
     recentClients.recentClients().then(function(response) { 
      // console.log(data); 
      $scope.loading = false; 
      $scope.client = response.data; 
     }); 
    } 

    // Initizialize function 
    reloadData(); 

    // Start Interval 
    var timerData = 
    $interval(function() { 
     reloadData(); 
    }, 1000); 

}]); 

    </script> 

</head> 
<body ng-app="ovwid" ng-controller="clientCtrl"> 

    {{ client }} 

</body> 
</html> 
0

정기적 인 서버 호출을 수행하도록 서비스를 설정할 수 있습니다. 나는이 코드를 잠시 후에 찾아 냈고 약간 수정했다. 내가 가지고있는 곳을 기억하고 싶다.

angular.module('my.services').factory('timeSrv',['$timeout',function($timeout){ 

    //-- Variables --// 

    var _intervals = {}, _intervalUID = 1; 

    //-- Methods --// 

    return { 
     setInterval : function(op,interval,$scope){ 
      var _intervalID = _intervalUID++; 

      _intervals[_intervalID] = $timeout(function intervalOperation(){ 
       op($scope || undefined); 
       _intervals[_intervalID] = $timeout(intervalOperation,interval); 
      },interval); 

      return _intervalID; 
     }, // end setInterval 

     clearInterval : function(id){ 
      return $timeout.cancel(_intervals[id]); 
     } // end clearInterval 
    }; // end return 
}]); // end timeSrv 

그리고 컨트롤러에 그렇게 같이 호출 할 것 :

$scope.getSomethingID = timeSrv.setInterval(function($scope){ 
    [... Do stuff here - Access another service ...] 
},10000,$scope); 

이 컨트롤러의 범위와 전달 기능을 10 초마다 실행됩니다. 다음과 같이 언제든지 취소 할 수 있습니다.

+0

당신은'$ interval'을 쉽게 대체 할 수 있습니다. 이 서비스를 작성할 때 버전 1.2 이전의 Angular를 다루고 있었다고 생각하십시오. –

관련 문제