一切都适用于简单类型,但我无法使用对象。
这是我的减速机:
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 })
],
成分:
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})
}
我在控制台中有这个状态:
Store {_isScalar: false, _dispatcher: Dispatcher, _reducer: Reducer, source: Store, select: function…}
而不是我的国家。为什么?
我认为错误在这里:
store.select('feeds');
但我不知道要传递给store.select()。
答案 0 :(得分:5)
我这样解决了,但我不确定这是好方法:
store.select('feedsReducer').subscribe((data: AppState) => this.state = data );
答案 1 :(得分:2)
这是一个能够推断类型的简单解决方案(比使用字符串更好):
store
.select(state => state.feeds)
.do(feeds => this.feeds = feeds)
.subscribe();
答案 2 :(得分:2)
你可以在模板中使用异步管道(记住feed是一个可观察的而不是数组):
-- feeds.component.ts
this.feeds = store.select(state => state.feeds)
-- feed.component.html
<li *ngFor="let feed of feeds | async">