Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
874 views
in Technique[技术] by (71.8m points)

angular - Ngrx Store Resets after browser refresh. How to make the application preserve the state?

I Dispatch a action from one component

this.store.dispatch({type : STORE_TEAMCREST , payload : team.crestURI});

and in the other component i select from the store using

this.store.select(state => state.table.teamCrest).subscribe(data => this.teamCrest = data);

This works fine if my app is going sequentially backward or forward, but once i do a browser refresh the state loses it's value. How to preserve it's value so that it works on browser refresh?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your store has a subscribe function which will be called any time an action is dispatched, and some part of the state tree may potentially have changed. For a simple solution, you could persist the state to local storage here:

this.store.subscribe(function() {
    localStorage.setItem('state', JSON.stringify(this.store.getState()));
})

Documentation here

Notice that you will need to stringify your state to store it in local storage

To use this state, you will need to pass the local storage state localStorage.getItem('state') (if it exists) as your default state in your reducer. To achieve this, i normally have a helper function check whether an item with key 'state' exists in local storage and calls JSON.parse on the value if it exists.

default reducer case:

default:
        if (retrieveState()) {
            var newState = JSON.parse(retrieveState())          
            return newState
        }
        else {
            return {...whatever your default state is};
        }

Also after a quick look around, there does appear to exist a middleware which should achieve what you are wanting: https://github.com/btroncone/ngrx-store-localstorage


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...