关于$ interval返回的承诺如何与Angular中的$ timeout进行比较的混淆

bin*_*nce 3 intervals angularjs angularjs-service

我有一个问题,了解$ interval返回的承诺如何在Angular中起作用.

比方说,在下面的例子中,我们有一个简单的"API"工厂被称为一个"getStuff",它返回一个项目阵列的方法.我们还有一个控制器在该工厂调用$ timeout:

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);
      });
  })
Run Code Online (Sandbox Code Playgroud)

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

所以假设我想通过用$ interval替换$ timeout来每秒调用该方法.现在没有任何反应

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);
      });
  })
Run Code Online (Sandbox Code Playgroud)

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

我感谢所有的帮助!

Sam*_*mmi 8

将计数值添加到DIMM Reaper在对Christophe L'的回答中提供的示例中:http://jsfiddle.net/a6u80jvn/7/

var app = angular.module("app", []);

app.run(function ($interval) {
    console.log('This fiddle will self destruct...');
    
    var timer = $interval(function (count) {
        console.log('tick... ' + count);
    }, 500, 4, false);
    
    timer.then(function(res) {
        console.log("BOOM! " + res);
    });
});
Run Code Online (Sandbox Code Playgroud)

输出:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>

<body ng-app="app">
</body>
Run Code Online (Sandbox Code Playgroud)

最终结果是最终计数.