[Angular 2] Passing Template Input Values to Reducers

本文介绍如何使用 Angular2 创建一个实时更新的数字时钟组件。该组件通过输入框接收用户设定的时间增量,并利用 RxJS 的 Observable 和 Subject 来响应按钮点击事件及定时更新时钟显示。

Angular 2 allows you to pass values from inputs simply by referencing them in the template and passing them into your Subject.next() call. This lesson shows you how to make a number input and pass the value so you can configure how much you want the clock to change.

 

/**
 * Created by wanzhen on 26.4.2016.
 */
import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/scan';
import 'rxjs/add/operator/mapTo';
import {Subject} from "rxjs/Subject";
import {Store} from '@ngrx/store';
import {SECOND, HOUR} from './reducer';

@Component({
    selector: 'app',
    template: `
        <input #inputNum type="number" value="0">
        <button (click)="click$.next(inputNum.value)">Update</button>
        <h1>{{clock | async | date:'yMMMMEEEEdjms'}}</h1>
        `
})
export class App {
    click$ = new Subject()
            .map( (number) => ({type: HOUR, payload: parseInt(number)}));

    seconds$ = Observable.interval(1000)
        .mapTo({type: SECOND, payload: 1});

    clock;

    constructor(store:Store) {
        this.clock = store.select('clock');


        Observable.merge(
            this.click$,
            this.seconds$
            )
            .subscribe((action)=>{
                store.dispatch(action)
            })
    }
}

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值