zoukankan      html  css  js  c++  java
  • [Angular 2] Using ngrx/store and Reducers for Angular 2 Application State

    ngrx/store is a library that simplifies common RxJS patterns for managing state and gives you an easy api to use it within your Angular 2 application. This lesson shows how to convert a common startWith and scan stream into an ngrx Store and reducer.

    // 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
    * */
    // 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';
    
    @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('hour'),
                Observable.interval(1000).mapTo('second')
                )
                .subscribe((type)=>{
                    store.dispatch({type})
                })
        }
    }
    // reducer.ts
    
    export const clock = (state = new Date(), {type})=> {
        const date = new Date(state.getTime());
        switch(type){
            case 'second':
                date.setSeconds(date.getSeconds() + 1);
                return date;
    
            case 'hour':
                date.setHours(date.getHours() + 2);
                return date;
    
        }
    
        return state;
    };
  • 相关阅读:
    14.3
    14.2
    14.1
    第14章 抽象类和接口
    13.5
    JAVA异常处理
    12.9
    12.7
    vs 常用快捷键
    click()和onclick()的区别
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5436259.html
Copyright © 2011-2022 走看看