简体   繁体   中英

Angularjs $interval returns fn is not a function

I want to check if cookie exists with $interval. I am calling $interval on page load. 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(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.

$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. In my Controller for a chart I want to refresh every 5 minutes, I added this at the end. First I call my refreshChart function, so the chart loads immediately the first time the page is loaded or refreshed. Then I call the $scope.Repeat function last in my controller. And my chart refreshes every 5 minutes, yay!

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

    $scope.refreshChart();

    $scope.Repeat();

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