我使用@ngrx/store、@ngrx/efffects 创建了以下 Angular 2 应用程序
@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 正常构建。
编辑:我已经进行了这些修改,但我看到问题是状态在层次结构的第一级具有减速器对象,它包含实际状态。此外,如果我添加第二个减速器,它永远不会像mainStoreReducer
. 这里有问题