简体   繁体   English

如何在指定时间(计划任务)后调用 Angular js 中的 api 端点?

[英]how to call api endpoint in Angular js after specif time (scheduled Task)?

i have the following service that get some data from an API and it works fine我有以下服务可以从 API 获取一些数据,并且工作正常

i call this service in the app.run() method我在 app.run() 方法中调用此服务

// some code...

$scope.pageStudents;

    $scope.getStudentsPage = function(){

        $http({
              method: 'GET',
              url: 'studentsResource/students'
            }).then(function successCallback(response) {

                $scope.pageStudents = response.data;

              });

    };


    //i want to call this method every 5 min for example.
    $scope.getStudentsPage();

my issue is how i can call my $scope.getStudentsPage();我的问题是如何调用我的$scope.getStudentsPage(); after each 5 min , something like scheduled job (like quartz in java) , is angular or javascript support this concept ?每 5 分钟后,类似于预定作业(如 java 中的石英),angular 或 javascript 是否支持这个概念? please anyone can guide me on how to achieve this operation.请任何人都可以指导我如何实现此操作。 thanks in advance.提前致谢。

If you want to take a delayed action once, then you can use angular's $timeout service.如果你想进行一次延迟动作,那么你可以使用 angular 的$timeout服务。 If you want it to happen multiple times, there's the $interval service.如果您希望它多次发生,则可以使用$interval服务。

So like this:所以像这样:

$scope.pageStudents;

$scope.getStudentsPage = function(){
    $http({
        method: 'GET',
        url: 'studentsResource/students'
    }).then(function successCallback(response) {
        $scope.pageStudents = response.data;
    });
};

$interval(function () {
    $scope.getStudentsPage();
}, 300000); // <--- 5 minutes in milliseconds

In plain javascript, you would use window.setTimeout or window.setInterval to do this.在纯 javascript 中,您将使用 window.setTimeout 或 window.setInterval 来执行此操作。 In angularjs you should instead use the $timeout and $interval services, because angularjs won't be able to run its change detection correctly otherwise.在 angularjs 中,您应该改为使用 $timeout 和 $interval 服务,因为否则 angularjs 将无法正确运行其更改检测。

Documentation for $timeout and $interval can be found here: $timeout 和 $interval 的文档可以在这里找到:
https://docs.angularjs.org/api/ng/service/$timeout https://docs.angularjs.org/api/ng/service/$timeout
https://docs.angularjs.org/api/ng/service/$interval https://docs.angularjs.org/api/ng/service/$interval

And for setTimeout and setInterval here:对于 setTimeout 和 setInterval 在这里:
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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