[英]Why is ngrx storing only first element of an array?
我有一个从REST服务收到的数组,正在尝试将其存储在我的ngrx存储中。 查看我的reducer,可以将控制台的每个元素打印到控制台。 但是,一旦我将其存储在状态中,它就会减少为单个元素。
这是我在化简器中得到的数组:
[
{"key1": "value1", "key2": "value2"},
{"key3": "value3", "key4": "value4"},
{"key5": "value5", "key6": "value6"},
{"key7": "value7", "key8": "value8"}
]
这是我在reducer中使用的代码:
switch (action.type) {
...
case actions.GET_ITEMS_COMPLETE:
console.log('the array');
console.log(action.items);
console.log('indiviual items');
console.log(action.items[0]);
console.log(action.items[1]);
console.log(action.items[2]);
console.log(action.items[3]);
return {...state,
items: action.items
};
...
}
请注意,我能够将数组的每个元素打印到控制台而没有问题,但是当我打印数组并在化简器完成后检查状态时,我看到的数组如下:
[{"key1": "value1", "key2": "value2"}]
谁能解释一下为什么其他三个元素从数组中被莫名其妙地删除了吗?
UPDATE按照以下要求,这些操作,效果,选择器和服务与reducer一起使用,以将项目持久化到状态:
动作
export const GET_ITEMS = '[Items] GET_ITEMS';
export const GET_ITEMS_COMPLETE = '[Items] GET_ITEMS_COMPLETE';
export const GET_ITEMS_ERROR = '[Items] GET_ITEMS_ERROR';
export class GetItemsAction implements Action {
readonly type = GET_ITEMS;
constructor() { }
}
export class GetItemsCompleteAction implements Action {
readonly type = GET_ITEMS_COMPLETE;
constructor(public items: Array<Item>) { }
}
export class GetItemsErrorAction implements Action {
readonly type = GET_ITEMS_ERROR;
constructor(public error: Response) { }
}
影响
@Effect()
getItems$ = this.actions$
.ofType(itemActions.GET_ITEMS)
.map(action => itemActions.GetItemsAction)
.switchMap(() => {
return this.api.item.getAll()
.map(returnedItems => new itemActions.GetItemsCompleteAction(returnedItems))
.catch(error => Observable.of(new itemActions.GetItemsErrorAction(error)))
});
选择器
export function getItems(): Selector<AppState, Array<Item>> {
return state$ => state$.map(state => state.item.items);
}
服务
@Injectable()
export class ItemService {
itmes$: Observable<Array<Item>>;
constructor(private store$: Store<AppState>) {
this.items$ = store$.let(getItems());
}
getItems() {
this.store$.dispatch(new GetItemsAction());
}
}
更新2在我的item对象的订阅之一中发现了问题。 如下图所示,其中有一个接头正在除去除第一个元件以外的所有元件。 现在我的问题是,订阅中的此拼接如何修改我的状态? Ngrx中的状态不是应该不变的吗?
this.itemService.items$.subscribe(value => this.items = value.splice(1,3));
布兰登,
我知道文档说商店是一成不变的,但这并不是我的经验。 也许我想念一些东西。 我花了太多时间去看一个看起来像这样的错误。
要使其不可变,您必须使用第三方程序包。 也许是Immutable.js或ngrx-store-freeze。
上面的代码不会修改您的ngrx状态,而是会修改您组件的状态,特别是组件items
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.