我有一个简单的倒计时器,角度为4
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/timer';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
countDown;
counter = 60;
enableButton:boolean = false;
this.countDown = Observable.timer(0,1000).take(this.counter).map(() => --
this.counter);
我希望在完成此observable时使enableButton布尔为true。
我该如何编写该代码?请帮忙
这是一个plunker链接,我在我的项目中使用它 https://plnkr.co/edit/TWMIEd1UykUdUC37qyFK?p=preview
答案 0 :(得分:4)
在视图中:
countDown;
counter = 10; // change accordingly
tick = 1000;
constructor() {
this.countDown = Observable.timer(0, this.tick)
.take(this.counter)
.map(() => --this.counter)
}
并在课堂上:
id
答案 1 :(得分:2)
您可以利用扫描和异步优势:
@Component({
selector: 'my-app',
template: `
<div>
<h1>Countdown timer</h1>
<h2>{{countDown | async}}</h2>
<button [disabled]="(countDown | async) === 0">My button</button>
</div>
`,
})
export class App {
countDown;
counter = 10;
constructor() {
this.countDown = Observable.timer(0,1000)
.scan((current, next) => this.counter - next)
.takeWhile(counter => counter >= 0);
}
}
以下是实时版:https://plnkr.co/edit/bKESzNK1wqbtPmQk4TUT?p=preview
因此,不是更新全局计数器,而是使用scan来保持本地版本的计数(因为计时器按顺序返回数字)
您可以使用.takeWhile
运算符
this.countDown = Observable.timer(0,1000)
.take(this.counter)
.map(() => --this.counter)
.takeWhile(counter => counter >= 0);
这是更新的plnkr:https://plnkr.co/edit/Z6K5Yt2tDS4MKbgIoujc?p=preview
您实际上不需要.take
,可以这样做:
this.countDown = Observable.timer(0,1000)
.map(() => this.counter--)
.takeWhile(counter => counter >= 0);
答案 2 :(得分:-1)
http://reactivex.io/documentation/operators/subscribe.html第三个论点
你可以这样做:
this.countDown = Observable
.timer(0, 1000)
.take(this.counter)
.map(() => --this.counter);
this.countDown.subscribe(() => {}, () => {}, () => (this.enableButton = true))
或者像这样:
<button *ngIf="!(countDown | async)"><button>
<button *ngIf="this.counter"><button>