简体   繁体   中英

Angular 6 + Ngrx state value update without using action

I have a simple state :

export interface ItemsState{
  items: Item[],
  otherItem: OtherItem,
}

const initialState: ItemsState= {
  items: [],
  otherItem: {} as OtherItem,
}

And a selector :

const getItemFeatureState = createFeatureSelector<ItemsState>('items');

export const getItemValue= createSelector(
  getItemFeatureState,
  state => state.otherItem,
);

In my component I use the selector :

 public item: Item  = {} as Item;

 constructor(private itemsStore: Store<fromItem.State>) {
    this.itemsStore.pipe(
      select(fromItem.getItemValue),
      distinctUntilChanged(),
    ).subscribe(item=> this.item = item);
}

But when I update this local Item by doing something simple like :

this.item.value = someValue;

this.item.value will be updated in ItemsState without using any Actions.

How is that possible ?

This is because the item is sharing the same reference. If you update it, your item in the store will also be updated.

This is NOT what you want. To catch these "mistakes" during development you can use the package ngrx-store-freeze to prevent this.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM