混淆了$间隔作品返回的承诺相比如何在角$超时 [英] Confusion about how the promise returned by $interval works compared to $timeout in Angular

查看:127
本文介绍了混淆了$间隔作品返回的承诺相比如何在角$超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解如何通过$间隔返回的承诺,在角工作的问题。

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

让我们在下面的例子说,我们有一个简单的API工厂被称为一个getStuff,它返回一个项目阵列的方法。我们也有一个控制器上工厂调用$超时:

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秒钟后,这是伟大的日志[东西]在控制台中。

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

因此​​,可以说我要调用该方法每一秒用$间隔更换$超时。现在什么也没有发生:

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

什么是在这种情况下$超时和$间隔之间有什么不同?

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

我AP preciate所有帮助!

I appreciate all help!

推荐答案

您可以通过 $间隔返回的承诺,唯一要做的是取消(停止其执行):

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

您code或许应该是这​​样的:

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

这篇关于混淆了$间隔作品返回的承诺相比如何在角$超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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