与 Angular 中的 $timeout 相比,$interval 返回的承诺如何工作的困惑 [英] Confusion about how the promise returned by $interval works compared to $timeout in Angular

查看:15
本文介绍了与 Angular 中的 $timeout 相比,$interval 返回的承诺如何工作的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解 $interval 返回的承诺如何在 Angular 中工作时遇到问题.

I'm having an issue understanding how the promise returned by $interval works in Angular.

假设在下面的示例中,我们有一个简单的api"工厂,其中包含一个名为getStuff"的方法,该方法返回一个包含一项的数组.我们还有一个控制器,该控制器在该工厂上调用 $timeout:

Let's say in the following example, we have a simple "api" factory with a method called "getStuff" that returns an array with one item. We also have a controller that calls $timeout on that factory:

angular.module("app",[])
  .factory('api', function(){
    return {
      getStuff: function() {      
        return ["stuff"];
      } 
    };   
  })
  .controller('appCtrl', function($scope, $timeout, api){
    $timeout(api.getStuff, 1000)
      .then(function(response){
        console.log(response);
      });
  })

这将在 1 秒后在控制台中记录 '["stuff"]',这很棒.

This will log '["stuff"]' in the console after 1 second, which is great.

所以假设我想通过用 $interval 替换 $timeout 每秒调用该方法.现在什么都没有发生:

So lets say I want to call that method every second by replacing $timeout with $interval. Now nothing happens:

angular.module("app",[])
  .factory('api', function(){
    return {
      getStuff: function() {      
        return ["stuff"];
      } 
    };   
  })
  .controller('appCtrl', function($scope, $interval, api){
    $interval(api.getStuff, 1000)
      .then(function(response){
        console.log(response);
      });
  })

在这种情况下,$timeout 和 $interval 有什么不同?

What is different between $timeout and $interval in this case?

感谢所有帮助!

推荐答案

对于 $interval 返回的 promise,你唯一能做的就是取消它(停止它的执行):

The only thing you can do with the promise returned by $interval is cancel it (to stop its execution):

var handle = $interval(someFunc, 1000);
...
$interval.cancel(handle);

您的代码应该如下所示:

Your code should probably look like:

app.controller('appCtrl', function($scope, $interval, api) {
    $interval(function() {
        console.log(api.getStuff());
    }, 1000);
});

为了幻想并看到一切协同工作:

To be fancy and see everything working together:

app.controller('appCtrl', function($scope, $interval, $timeout, api) {
    var handle = $interval(function() {
        console.log(api.getStuff());
    }, 1000);

    $timeout(function() {
        $interval.cancel(handle);
    }, 5000);
});

这篇关于与 Angular 中的 $timeout 相比,$interval 返回的承诺如何工作的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆