簡體   English   中英

如何使用ngrx-store調用正確的商店“集合”?

[英]How do I call into correct store 'collection' with ngrx-store?

我有兩個計數器和網址的數據集合(示例應用程序-試圖學習ngrx)。 我可以正確地拉出並顯示2個商店中的每個商店在其各自的組件中。 使用ngrx-store中的計數器示例,我還可以遞增和遞減計數器。 我為網址添加了一個reducer,現在在action開關中只有一個默認值。

問題:當我增加計數器時,也會觸發url默認操作。 我沒有正確選擇1個減速器上的1個動作。 我怎么做?

可能的答案?:我認為每個異徑管的動作需要不同嗎? 即,“計數器增量”和“ URL增量”相對於使用“增量”的兩個縮減器? 還是有另一種方法?

我是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;
    }
}

您應該添加distinctUntilChanged運算符。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM