简体   繁体   English

Angularjs $ interval返回fn不是函数

[英]Angularjs $interval returns fn is not a function

I want to check if cookie exists with $interval. 我想检查cookie是否存在$ interval。 I am calling $interval on page load. 我在页面加载时调用$ interval。 This call periodically throws an error: 此调用会定期抛出错误:

> 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)

I really don't understand why. 我真的不明白为什么。

Here is my code: 这是我的代码:

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);
    }
}]);

Code is being called from $document.ready: 从$ document.ready调用代码:

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

You added the result of the function instead of the function itself. 您添加了函数的结果而不是函数本身。 Calling $scope.CheckLoginCookie() will return undefined , but $interval expects a callback instead. 调用$scope.CheckLoginCookie()将返回undefined ,但$interval需要回调。

$interval($scope.CheckLoginCookie, 1000);

If the function requires parameters, just use it like this: 如果函数需要参数,只需使用它:

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

I used Str's answer, and it worked for me. 我使用了Str的答案,它对我有用。 In my Controller for a chart I want to refresh every 5 minutes, I added this at the end. 在我的控制器中,我希望每隔5分钟刷新一次图表,最后我添加了这个。 First I call my refreshChart function, so the chart loads immediately the first time the page is loaded or refreshed. 首先我调用我的refreshChart函数,因此图表会在第一次加载或刷新页面时立即加载。 Then I call the $scope.Repeat function last in my controller. 然后我在我的控制器中调用$ scope.Repeat函数。 And my chart refreshes every 5 minutes, yay! 我的图表每5分钟刷新一次,是的!

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

    $scope.refreshChart();

    $scope.Repeat();

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

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