[Angular 2] Mapping Streams to Values to Affect State

本文介绍如何利用Angular2和RxJS库中的Observables、Operators等特性实现一个带有按钮控制的实时计时器应用。通过点击按钮可以增加一小时的时间,同时每过一秒会自动更新显示的时间。

While you have multiple streams flowing into your scan operator, you'll need to map each stream to the specific values you need to update your state the way that you want. This lesson covers using the map operator to determine what the click and interval should do when the state is updated.

 

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/scan';
import 'rxjs/add/operator/startWith';
import {Subject} from 'rxjs/Subject';

@Component({
    selector: 'app',
    template: `
        <button (click)="click$.next()">Add one second</button>
        <h1>{{clock | async | date: 'yMMMMEEEEdjms'}}</h1>
    `
})

class App {

    click$ = new Subject();
    clock;
    constructor(){

        this.clock = Observable.merge(
            Observable.interval(1000).mapTo('second'),
            this.click$.mapTo('hour')
        )
            .startWith(new Date())
            .scan( (acc: Date, curr: string) => {
                // acc: new Date() passed from startWIth
                // curr: string, passed from mapTo
                console.log(acc, curr);
                const date: Date = new Date(acc.getTime());
                if(curr === "second"){
                    date.setSeconds(date.getSeconds() + 1);
                }

                if(curr === "hour"){
                    date.setHours(date.getHours() +1 );
                }

                return date;
            });
    }
}

bootstrap(App);

 

转载于:https://www.cnblogs.com/Answer1215/p/5436090.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值