[Angular 2] Using a Value from the Store in a Reducer

RxJS allows you to combine streams in various ways. This lesson shows you how to take a click stream and combine it with a store stream to use a value from the store inside a reducer.

The logic is when we click the recall button, it will reset all the people's time to the current time.

First, bind the click event to recall$:

<button (click)="recall$.next()">Recall</button>

...

recall$ = new Subject();

We get the latest time from the time stroe:

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


        Observable.merge(
            this.click$,
            this.seconds$,
            this.person$,
            this.recall$
                .withLatestFrom(this.time, (_, y) => y) // _: means don't need to care about the first param which is this.recall$
                .map( (time) =>  ({type: RECALL, payload: time}))
            )
            .subscribe(store.dispatch.bind(store))
    }

_: is naming convention, it means, don't care about the first value.

Last, we handle the action in reducer:

        case RECALL:
            return state.map( (person) => {
                return {
                    name: person.name,
                    time: payload
                };
            })

-------------

原文地址:https://www.cnblogs.com/Answer1215/p/5441173.html