【问题标题】:Angular 2 and the function $intervalAngular 2 和函数 $interval
【发布时间】:2016-07-23 16:37:16
【问题描述】:

如何在 Angular2 中重写并在 Angular1 中 Dart 代码:

$interval(function () {
    if($scope.carouselIndex < $scope.showcases.length -1){
      $scope.carouselIndex = $scope.carouselIndex + 1;
    } else {
      $scope.carouselIndex = 0;
    }

  }, properties.delay);

我尝试过这种方式但没有奏效:

 carouselIndex = 0;
          for(int i=0; i<contents.size(); i++){
            if(carouselIndex < contents.length -1){
              setTimeout(function() {
              carouselIndex = carouselIndex + 1;
              }, 1000);
            } else {
              carouselIndex = 0;
            }
      }

有什么想法吗? 谢谢

【问题讨论】:

    标签: dart angular carousel settimeout setinterval


    【解决方案1】:

    你可以试试Observable.interval方法:

    Observable.interval(properties.delay).subscribe(() => {
      if (this.carouselIndex < this.showcases.length - 1) {
        this.carouselIndex = this.carouselIndex + 1;
      } else {
        this.carouselIndex = 0;
      }
    });
    

    每次达到延迟时都会触发一个事件。所以订阅时定义的回调会被相应地调用。

    在您的情况下,您尝试将同步循环与异步处理与setTimeout 函数混合使用。

    【讨论】:

      【解决方案2】:

      您可以为此使用Timer 类:

        Timer _timer;
      
        someFunc() {
          _timer = new Timer.periodic(const Duration(milliseconds: 1000 /*properties.delay*/),
              (_) {
            if (this.carouselIndex < this.showcases.length - 1) {
              this.carouselIndex = this.carouselIndex + 1;
            } else {
              this.carouselIndex = 0;
            }
          });
      
          // to stop the periodic execution use
          // _timer.cancel();
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-15
        • 2018-10-18
        • 2017-06-05
        • 1970-01-01
        • 2017-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多