简体   繁体   中英

how to remove all data from ngrx store?

I have a state which contains an array of data. I need to remove all data from that array when certain action done. I use Angular 2.

const intialState: State = {   
    someData: new Array<someData>()
};

export function stateReducer(state = intialState, action: StateActionList.StateActionList) {
    switch (action.type) {
    case StateActionList.REMOVE_DATA:
            console.log(state.someData);
            return {
                ...state,
                someData: new Array<someData>()
            }
        }
}

In my component I have following code:

this.store.dispatch(new StateActions.RemoveData());

In State actions:

export const REMOVE_DATA="REMOVE_DATA";
export class RemoveData implements Action {
    readonly type=REMOVE_DATA;
}

That code doen't return for me cleaned array someData from the store. The array contains same data as it was before

Try explicitly returning an empty array as the new state:

case StateActionList.REMOVE_DATA:: {
  return {
    someData: []
  };
}

This looks a bit doubtful

someData: new Array<someData>()

someData is a variable name and a type?

See Declare an array in TypeScript

let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();

let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();

let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];

let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();

 const state = { someData: new Array() }; console.log('empty', state.someData) state.someData.push('a') console.log('contains "a"', state.someData) const remove = () => { console.log('constians "a"', state.someData); return { ...state, someData: new Array() } } const newState = remove() console.log('empty', newState.someData) 

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