【问题标题】:Updating textview at a interval using Angular $interval使用 Angular $interval 定期更新 textview
【发布时间】:2018-02-01 07:41:13
【问题描述】:

我还是 Ionic 的新手,尤其是 Angular。 我想用一个从 10 到 0 的数字更新一个 textview 并每秒更新一次。

在我的课堂上,我有一个属性public timeLeft: string = 'Your timer';,它使用<div>{{timeLeft}}</div>绑定到html

我尝试使用常规 JavaScript setInterval(),但是当我尝试使用关键字 this 更新属性 timeLeft 时它失败了,因为 this 与运行 setInterval 时的类不在同一范围内功能。

我读到我应该使用Angular function$interval,因为它可以访问相同的范围或视图,我不太了解那部分。

我发现一些代码说我应该制作一个控制器,它应该包含类似于myApp.controller(function($scope, $interval) {...}) 的内容

在 Ionic 博客上,我发现一篇文章提到一些 Angular 1 概念作为控制器和范围已经过时了。

所以我的问题是。如何使用 Angular $interval 在 Ionic 中每隔一段时间更新一个文本视图?一个完整的代码示例会很棒,因为我真的迷失在这里了。

  • cli-utils:1.9.2
  • 离子 CLI:3.9.2
  • 科尔多瓦 CLI:6.5.0
  • 离子应用脚本:2.1.3
  • 离子框架:离子角 3.6.0

【问题讨论】:

标签: angular typescript ionic-framework observable ionic3


【解决方案1】:

您可以在此处使用Observable.timer。请尝试以下代码。

创建一个在 initialDelay 之后开始发射的 Observable 和 在此后的每个时间段之后发出越来越多的数字。

类似于间隔,但您可以指定何时应该排放 开始。

这里是working Plunker

import {Component} from '@angular/core'
import {Observable} from 'rxjs/Observable'
import 'rxjs/add/observable/timer'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/take'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h1>Countdown timer</h1>
      <h2>{{timeLeft | async}}</h2>
    </div>
  `,
})
export class MyApp {

  timeLeft;
  counter = 10;
  constructor() {

    this.timeLeft = Observable.timer(1000,1000)
      .take(this.counter)
      .map(() => --this.counter)

  }
}

更新:

html

 <h2>{{timeLeft}}</h2>

.ts

 Observable.timer(1000,1000)
      .take(this.counter)
      .map(() => --this.counter).subscribe(val => {
          //you can do transformation here
       }

【讨论】:

  • 谢谢你的例子,我使用毫秒,然后一次倒计时一秒,我需要使用暂停/停止来跟踪。我的问题是,不是将数字写入视图,我是否可以得到数字,然后让剩余的毫秒数像这样var date = new Date(timerLength - timerProgress); this.timeLeft = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
  • 是的,您可以这样做。您需要为此使用momentJs。请参阅:stackoverflow.com/a/45796889/1077309
  • 我明白了,但我的意思是 Observable 直接向视图返回一个数字,我想在将其放入视图之前处理该数据。 timerLength 是计时器的多长时间(以毫秒为单位), timerProgress 是我在计时器中的距离。然后我可以将两者相减以获得剩余时间,并从中使其易于阅读并将其放到视图中。
  • 请参阅上面的更新。
猜你喜欢
  • 1970-01-01
  • 2018-11-16
  • 2013-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
相关资源
最近更新 更多