zoukankan      html  css  js  c++  java
  • [Angular 2] Dispatching Action with Payloads and type to Reducers

    While action types allow you tell your reducer what action it should take, the payload is the data that your reducer will use to update the state. 

    // reducer.ts
    
    export const SECOND = "SECOND";
    export const HOUR = "HOUR";
    
    export const clock = (state = new Date(), {type, payload})=> {
        const date = new Date(state.getTime());
        switch(type){
            case SECOND:
                date.setSeconds(date.getSeconds() + payload);
                return date;
    
            case HOUR:
                date.setHours(date.getHours() + payload);
                return date;
    
        }
    
        return state;
    };
    //app.ts
    
    /**
     * 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: `
            <button (click)="click$.next()">Update</button>
            <h1>{{clock | async | date:'yMMMMEEEEdjms'}}</h1>
            `
    })
    export class App {
        click$ = new Subject();
    
        clock;
    
        constructor(store:Store) {
            this.clock = store.select('clock');
    
    
            Observable.merge(
                this.click$.mapTo({type: HOUR, payload: 1}),
                Observable.interval(1000).mapTo({type: SECOND, payload: 1})
                )
                .subscribe((action)=>{
                    store.dispatch(action)
                })
        }
    }
    // main.ts
    
    import {bootstrap} from 'angular2/platform/browser';
    import {App} from './app';
    import {provideStore} from '@ngrx/store';
    import {clock} from './reducer';
    
    bootstrap(App, [
        provideStore({clock})
    ]).then(
        ()=> console.log('App running...'),
        err=> console.log(err)
    );
    
    /*
    *  1. Create a reducer
    *  2. Use provideStore({reducer_name}) to provide store
    *  3. Use store.select('reducer_name') to get store in Observable type
    *  4. Apply logic to dispatch the action
    * */
  • 相关阅读:
    composer "Failed to decode zlib stream"
    敏捷开发 角色英文简称
    MySQL索引背后的数据结构及算法原理 (转)
    Jenkins mac pkg安装 后默认配置文件/启动路径
    react componentWillReceiveProps 使用注意
    charles https抓包 (安卓安装证书)
    error_reporting()
    PHP开发API接口及使用
    封装pdo单例模式类
    php 将多个txt文件合并成
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5437348.html
Copyright © 2011-2022 走看看