我已經創建了下面的角2應用程序與@ NGRX /店,@ NGRX/efffects@ NGRX /存儲不訂閱正確選擇
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
SharedModule,
StoreModule.provideStore({mainStoreReducer}),
EffectsModule.run(MainEffects)
],
providers: [
StompService
],
bootstrap: [AppComponent]
})
export class AppModule { }
export interface State {
counter: number;
persons: any[];
personsLoaded : boolean;
}
export const initialState: State = {
counter: 10,
persons: [],
personsLoaded: false,
};
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
data$;
persons$;
personForm: Person = <Person>{};
persons = [];
// state: State;
constructor(private store: Store<State>,
private http: Http,
private stomp: StompService) {
// console.log(`We have a store! ${store}`);
this.store.dispatch(CounterService.requestUsers);
this.persons$ = store.select((state: State) => state.persons);
this.data$ = store.select((state: State) => `Data is: ${state.counter}`);
}
}
export interface Person {
name: string,
surname: string
}
<ul>
<li *ngFor="let person of persons$ | async; let i = index">{{i}}. {{person.name}} {{person.surname}}</li>
</ul>
@Injectable()
export class MainEffects {
constructor(private action$: Actions,
private http: Http) {
}
@Effect() users$ = this.action$.ofType(CounterService.REQUEST_USERS)
.switchMap(() => this.http.get("api/persons"))
.map(res => res.json())
.map(json => json._embedded.persons)
.do(json => console.log(json))
.switchMap(result => Observable.of(CounterService.receivedUsers(result)));
}
export const mainStoreReducer: ActionReducer<State> =
(state = initialState, action: Action) : State => {
console.log(`Action came in ! ${action.type}`);
switch (action.type) {
case CounterService.RECEIVED_USERS: {
return {
counter: state.counter,
persons: action.payload,
personsLoaded: true
};
}
case CounterService.REQUEST_USERS: {
console.log("requested users");
return state;
}
default: {
return state;
}
}
};
好了,所以似乎與這些線路的問題:
`StoreModule.provideStore({mainStoreReducer})` and
this.persons$ = store.select((state: State) => state.persons);
當我使用{}
mainStoreReducer
選擇似乎並沒有正常工作。但是,如果我做StoreModule.provideStore(mainStoreReducer)
那麼它奇蹟般地工作!顯然,我不能這樣做,因爲那只是一個減速器,所以在一個正常的項目中我會有多個減速器。
任何人都有一個想法出了什麼問題。如果你喜歡,請直接看看github項目https://github.com/cgeo7/ngrx_tests_websockets_spring-boot 它的構建正常。
編輯:我做了這些修改,但我看到問題是狀態具有reducer對象在層次結構的第一級,它包含實際狀態。此外,如果我添加第二個減速器,則永遠不會像mainStoreReducer
那樣進行初始化。有你需要的減速導出到單一的「減速」有鬼這裏
這不是ES6中鍵值對{myreducer}的問題,基本上將其轉換爲{myreducer:my reducer} – ChrisGeo