【问题标题】:$timeout for $http with specific URL AngularJS具有特定 URL AngularJS 的 $http 的 $timeout
【发布时间】:2018-12-23 19:05:57
【问题描述】:

这是我的代码: JS:

var timer;
$scope.getapi_url = function(n){
       var url = n;
        $http({
            method: 'GET',
            url: url,
        })
            .then(function successCallback(data) {
                $scope.data = data.data;
                console.log($scope,data);
                timer = $timeout($scope.getapi_url(), 5000);
            }, function errorCallback(response) {
                $scope.errorBackend = true;
                console.log(response);
                console.log('error');
            });
    };

HTML:

<button class="btn btn-clear btn-sm" ng-click="getapi_url('myurl') ">Click!</button>

在第一个$timeout 之后,我收到了一个错误,类似于n is undefinded

我能用它做什么?

提前感谢所有答案!!!

【问题讨论】:

  • 您是否将vm$scope 混为一谈?你的 HTML 代码有 controllerAs 语法吗?
  • @AlekseySolovey 是的,实际上我有 var vm = this;并且它与 $scope 混合 - 这可能是个问题吗?
  • 我很困惑为什么你同时拥有$scope.getapi_urlvm.getapi_url
  • 哦,这是我写这个答案的错误
  • 在我的代码中我只有 vm

标签: angularjs http timeout


【解决方案1】:

试试这个,但它永远不会停止,你必须使用 $timeout.cancel(timer); 手动停止。

var timer;
$scope.getapi_url = function (n) {
    var url = n;
    $http({
            method: 'GET',
            url: url,
        })
        .then(function successCallback(data) {
            $scope.data = data.data;
            console.log($scope, data);
            timer = $timeout($scope.getapi_url(n), 5000); 
            // passing n if you don't want check n value on starting of function.
        }, function errorCallback(response) {
            $scope.errorBackend = true;
            console.log(response);
            console.log('error');
        });
};

【讨论】:

  • @bafix2203 您可以在调用 $http 之前编写条件。 if(n) 然后调用 API else 跳过。
猜你喜欢
  • 2014-08-13
  • 1970-01-01
  • 2021-09-22
  • 2018-07-14
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多