如何使用ngrx-store调用正确的商店'集合'?

时间:2016-10-28 21:46:57

标签: angular javascript-events rxjs reducers ngrx

我有两个数据集合(示例应用程序 - 试图学习ngrx)的计数器和网址。我可以正确地拉出并显示各自组件中的2个商店。使用ngrx-store中的计数器示例,我也可以增加&递减柜台。我为url添加了一个reducer,它现在只在action开关中有一个默认值。

问题:当我增加计数器时,也会触发url默认操作。我没有正确选择1个减速器上的1个动作。我怎么做?

可能的答案?:我认为每个减速机的动作需要明确吗?即,'反增量'和'url-increment'与使用'增量'的两个减速器相比?还是有另一种方法吗?

我是ngrx和rxjs的新手,所以最简单/最直接的代码会有所帮助。

// app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import 'rxjs/Rx';
import '@ngrx/core';
import { Store, StoreModule } from '@ngrx/store';

import { AppComponent  }  from './components/app.component';
import { UrlListComponent, UrlItemComponent, ListComponent, ListItemComponent, CounterComponent } from './components/index'
import {  counterReducer, urlReducer} from './reducers/index';

@NgModule({
  imports: [ 
    BrowserModule, 
    FormsModule, 
    HttpModule,
    StoreModule.provideStore({counter: counterReducer, urls: urlReducer}) 
    ],
  declarations: [ AppComponent, UrlItemComponent, UrlListComponent, ListComponent, ListItemComponent, CounterComponent],
  bootstrap: [ AppComponent]
})
export class AppModule { 
  constructor(){console.log("AppModule");}
}

// app.component.ts
import { Injectable, Component, Output, Input, EventEmitter, ChangeDetectionStrategy } from '@angular/core';
import { HttpModule  } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Store } from '@ngrx/store';
import { INCREMENT, DECREMENT, RESET, Url } from '../reducers/index';
import { ListComponent, UrlListComponent, CounterComponent} from './index'

export interface AppState {
  counter: number;
  urls : Url[]
}

@Component({
    moduleId: module.id, //system js variable name for relative path
    selector: 'my-app',
    template: `
        <counter-comp [counter]="counter" ></counter-comp>
        <url-list [urls]="urls"></url-list>
        <list [innerArray]="myarray"></list>
    `,
    providers: [],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
    counter: number;
    urls: Url[];
    myarray: number[] = [];

    constructor(private store: Store<AppState>){
        console.log('AppComponent constructor');

        this.store.select(state => state.counter)
            .subscribe(data => this.counter = data);
        this.store.select(state => state.urls)
          .subscribe(data => this.onUrlsEmitted(data));

        this.myarray.push(1);
        this.myarray.push(2);
        this.myarray.push(3);
    }

    ngOnInit() {
            console.log('AppComponent ngOnInit');
    }
    // executed once user data arrives from the store
    public onUrlsEmitted(data:Url[]){
        console.log('AppComponent onUrlsEmitted');
        this.urls = data;
        if(!data || !data.length){ 
            console.log("no url data arrived");
        }
    }
}

// counter.component.ts
import { Component, Input } from '@angular/core';
import { Url, AppState, INCREMENT, DECREMENT, RESET } from '../reducers/index';
import { Store } from '@ngrx/store';

@Component({
  selector: 'counter-comp',
  template: `
        <div class='counter'>
        <div>Current Count: {{ counter }}</div>
        <button (click)="increment()">Increment</button>       
        <button (click)="decrement()">Decrement</button>
        <button (click)="reset()">Reset Counter</button>
        </div>
  `
  ,
    styles:[`
        div { width: 100%; }
        .counter { background-color: #99bbff; }
    `]
})
export class CounterComponent {
  @Input() counter: number;

    constructor(private store: Store<AppState>){
    }

    increment(){
        console.log("counter.component.ts increment");
        this.store.dispatch({ type: INCREMENT });
    }

    decrement(){
        console.log("counter.component.ts decrement");
        this.store.dispatch({ type: DECREMENT });
    }

    reset(){
        console.log("counter.component.ts reset");
        this.store.dispatch({ type: RESET });
    }
    ngOnInit() {
        console.log('CounterComponent input: ' + this.counter);
    }
}

// counter.ts
import { ActionReducer, Action } from '@ngrx/store';

export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const RESET = 'RESET';

export const counterReducer: ActionReducer<number> = (state: number = 0, action: Action) => {
    console.log("counterReducer action.type " + action.type);
     console.log(JSON.stringify(state));
    switch (action.type) {
        case INCREMENT:
            return state + 1;

        case DECREMENT:
            return state - 1;

        case RESET:
            return 0;

        default:
            console.log("counterReducer default");
            return state;
    }
}
// url.ts
import { ActionReducer, Action } from '@ngrx/store';
//export const INCREMENT = 'INCREMENT';
//export const DECREMENT = 'DECREMENT';
//export const RESET = 'RESET';

export interface Url{
    id: number;
    name: string;
}

let initialState = function(){
    return [{id:1, name:"Dina"},{id:2, name:"Wayne"},{id:3,name:"kids"}];
}

export const urlReducer: ActionReducer<Url[]> = (state: Url[] = initialState(), action: Action) => {
     console.log("urlReducer action.type " + action.type);
     console.log(JSON.stringify(state));
     switch (action.type) {
        default:
            console.log("urlReducer default");
            console.log(state);
            return state;
    }
}

1 个答案:

答案 0 :(得分:0)

您应该添加distinctUntilChanged运算符。

this.store.select(state => state.urls).distinctUntilChanged().subscribe(data => this.onUrlsEmitted(data))