我在我的应用程序中使用ngrx / store而我在保存数组时遇到问题。我的数组在启动时设置为空:
export interface AppState{
customObjects: Array<CustomObject>;
};
export const initialState: AppState = {
customObjects: []
};
我正在尝试使用以下函数手动为其提供两个CustomObject的数组:
loadCustomObjects() {
let initialItems: CustomObject[] = [
{
directoryName: "d_name_1",
brokenLinks: 0,
},
{
directoryName: "d_name_2",
brokenLinks: 0,
}
];
this.appStore.dispatch({ type: LOAD_CUSTOM_OBJECTS, payload: initialItems });
}
调用此函数将调度我的reducer函数:
export const mainReducer:ActionReducer =(state:AppState,action:Action)=&gt; {
if (typeof state == 'undefined') {
state = initialState;
}
switch (action.type) {
case LOAD_CUSTOM_OBJECTS:
return Object.assign({}, action.payload)
default: {
return state;
}
}
}
这一切似乎都很好,但我的主应用程序组件的数组没有得到这两个对象。如果我手动设置默认状态以拥有这两个CustomObjects,那么它可以工作(我不能这样做,因为我需要能够随时更新数组)。我的HomeComponent使用:
customObjects$ Observable<Array<CustomObject>>;
constructor(private appStore: Store<AppState>) {
appstore.select('mainReducer')
.subscribe((data: AppState) => {
if (typeof data != 'undefined') {
this.customObjects$ = Observable.of(data.customObjects);
}
});
}
我已经分析了我的对象,我希望看到'this.customObjects $'最终成为两个CustomObjects的数组。相反,它是ScalarOservable:
ScalarObservable {_isScalar:true,value:undefined,scheduler:null}等。
注意 - 我不确定是否需要,但我在家庭组件的@Component部分中包含了ChangeDetectionStrategy.onPush。我也确保使用
StoreModule.provideStore({ mainReducer })
在我的app.module类中。
有谁知道我做错了什么以及为什么'this.customObjects $'不是两个对象数组?我是ngrx / store的新手 - 我觉得我的reducer函数设置数组的方式存在问题,但我不确定。
答案 0 :(得分:1)
我能够使用此代码:
存储相关代码:
export interface CustomObject {
directoryName: string;
brokenLinks: number;
}
export interface AppState {
Main: CustomObject[];
};
export function MainReducer(state: CustomObject[] = [], action: Action) {
switch (action.type) {
case LOAD_CUSTOM_OBJECTS:
return Object.assign({}, action.payload);
default: {
return state;
}
}
}
const reducers = {
Main: MainReducer
};
发送/收听商店的组件/服务
customObjects: CustomObject[];
constructor(private appStore: Store<AppState>) {
appStore.select(store => store.Main)
.subscribe(objs => {
this.customObjects = objs;
console.log(this.customObjects);
})
}
loadCustomObjects() {
let initialItems: CustomObject[] = [
{
directoryName: "d_name_1",
brokenLinks: 0,
},
{
directoryName: "d_name_2",
brokenLinks: 0,
}
];
this.appStore.dispatch({ type: LOAD_CUSTOM_OBJECTS, payload: initialItems });
}
异步管道版本:
customObjects$: Observable<CustomObject[]>;
constructor(private appStore: Store<AppState>) {
this.customObjects$ = appStore.select(store => store.Main);
}
loadCustomObjects() {
let initialItems: CustomObject[] = [
{
directoryName: "d_name_1",
brokenLinks: 0,
},
{
directoryName: "d_name_2",
brokenLinks: 0,
}
];
this.appStore.dispatch({ type: LOAD_CUSTOM_OBJECTS, payload: initialItems });
}
<div *ngFor="let customObj of customObjects$ | async"></div>