[英]Get data from ngrx/store
使用簡單類型,所有方法都可以正常工作,但是我無法使用對象。
這是我的減速器:
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})
}
我在控制台中有this.state:
Store {_isScalar: false, _dispatcher: Dispatcher, _reducer: Reducer, source: Store, select: function…}
而不是我的國家。 為什么呢
我認為這里的錯誤:
store.select('feeds');
但我不知道該如何傳遞給store.select()。
我像這樣修復它,但是我不確定這是個好方法:
store.select('feedsReducer').subscribe((data: AppState) => this.state = data );
這是一個能夠推斷類型的簡單解決方案(比使用字符串更好):
store
.select(state => state.feeds)
.do(feeds => this.feeds = feeds)
.subscribe();
您可以在模板中使用異步管道(請記住提要是可觀察的,而不是數組):
-- feeds.component.ts
this.feeds = store.select(state => state.feeds)
-- feed.component.html
<li *ngFor="let feed of feeds | async">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.