All works fine with simple types, but I can not manage to work it with objects.
Here is my reducer:
import { Action } from '@ngrx/store'
import { RssFeed } from "../rss/rss";
export interface AppState {
demoData: number;
feeds: RssFeed[];
}
const initialState: AppState = {
demoData: 0,
feeds: []
};
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export function feedsReducer(state: AppState = initialState, action: Action): AppState {
switch(action.type) {
case INCREMENT: {
return {
demoData: state.demoData + 1,
feeds: []
}
}
case DECREMENT: {
return {
demoData: state.demoData - 1,
feeds: []
}
}
default:
return state;
}
}
app.module:
import { StoreModule } from '@ngrx/store';
import { feedsReducer } from './actions/rss';
imports: [
StoreModule.provideStore({ feeds: feedsReducer })
],
component:
import {Store } from '@ngrx/store';
import { AppState, INCREMENT, DECREMENT } from '../actions/rss'
export class RssComponent {
state: Observable<AppState>;
constructor(private store: Store<AppState>) {
this.state = store.select('feeds');
addDemoData() {
console.log(this.state);
this.store.dispatch({type: INCREMENT})
}
I have in console for this.state:
Store {_isScalar: false, _dispatcher: Dispatcher, _reducer: Reducer, source: Store, select: function…}
instead of my State. Why ?
I think the error here:
store.select('feeds');
but I don't know what to pass to store.select().
我像这样修复它,但是我不确定这是个好方法:
store.select('feedsReducer').subscribe((data: AppState) => this.state = data );
Here's a simple solution that is capable of infering types (so better than using a string) :
store
.select(state => state.feeds)
.do(feeds => this.feeds = feeds)
.subscribe();
You can use async pipe it in the template(remember feeds is a observable not an array):
-- feeds.component.ts
this.feeds = store.select(state => state.feeds)
-- feed.component.html
<li *ngFor="let feed of feeds | async">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.