Angularjs$interval返回的fn不是函数

Angularjs $interval returns fn is not a function

本文关键字:函数 fn interval 返回 Angularjs      更新时间:2023-09-26

我想检查$interval的cookie是否存在。我在页面加载时调用$interval。这个调用周期性地抛出一个错误:

> TypeError: fn is not a function
>     at callback (angular.js:12516)
>     at Scope.$eval (angular.js:17444)
>     at Scope.$digest (angular.js:17257)
>     at Scope.$apply (angular.js:17552)
>     at tick (angular.js:12506)

我真的不明白为什么。

这是我的代码:

angular.module("appModule")
.controller("loginController", ["$scope", "$http", "$window", "$document", "$interval", "$cookies",
    function ($scope, $http, $window, $document, $interval, $cookies) {
    var stopInterval;
    $scope.CheckLoginCookie = function () {
        if ($cookies.get("Login") != null) {
            if (angular.isDefined(stopInterval)) {
                $interval.cancel(stopInterval);
                stopInterval = undefined;
            }
            $window.location.href = $scope.UrlNotes;
        }
    }
    $scope.Repeat = function ()
    {
        stopInterval = $interval($scope.CheckLoginCookie(), 1000);
    }
}]);

正在从$document.ready:调用代码

$document.ready(function () {      
    $scope.Repeat();
})

您添加了函数的结果,而不是函数本身。调用$scope.CheckLoginCookie()将返回undefined,但$interval需要回调。

$interval($scope.CheckLoginCookie, 1000);

如果函数需要参数,就这样使用:

$interval(function() {
    $scope.CheckLoginCookie(param1, param2);
}, 1000);

我使用了Str的答案,它对我有效。在我的控制器中,我想每5分钟刷新一次图表,我在最后添加了这个。首先,我调用refreshChart函数,以便在第一次加载或刷新页面时立即加载图表。然后我在控制器中最后调用$scope.Repeat函数。我的图表每5分钟刷新一次,耶!

    $scope.Repeat = function () {
        intervalPromise = $interval(function () {
            $scope.refreshChart();
        }, 300000);
    }
    $scope.refreshChart();
    $scope.Repeat();