I recently added ngrx store to my existing angular2 app in order to simplify the code and maintain a shared state. However I am confused about one part, I update my state from the server once in the beginning and after wards I just work on the state without checking the server. So what happens when for example some thing changes on the backend? Am i to check it every time when, I go the that page or is there a better way? Basically, I want to know what is the best practice for making sure that your state data is updated to show the server data?
It is recommended to use NGRX Effects. When you implement NGRX Effects along with the Store, any HTTP side effects are handled by the Effects, which in turn, will use an Action in the Store to update the data. An Effect listens for the Action and uses the payload of the Action to perform a side-effect(HTTP). When the Effect finishes, it calls a new Action(either an Action for success or an action for failure) with a new payload, thus updating the data in the Store.
In the example in the Effects docs it shows an Effect for Login
:
@Injectable()
export class AuthEffects {
constructor(
private http: Http,
private actions$: Actions
) { }
@Effect() login$ = this.actions$
// Listen for the 'LOGIN' action
.ofType('LOGIN')
// Map the payload into JSON to use as the request body
.map(action => JSON.stringify(action.payload))
.switchMap(payload => this.http.post('/auth', payload)
// If successful, dispatch success action with result
.map(res => ({ type: 'LOGIN_SUCCESS', payload: res.json() }))
// If request fails, dispatch failed action
.catch(() => Observable.of({ type: 'LOGIN_FAILED' }))
);
}
In this example, the Effect for Login listens for the LOGIN
action. When the LOGIN
action occurs, it uses the action's payload and performs an HTTP POST. When the HTTP POST returns, it either calls the action LOGIN_SUCCESS
with the json response for the payload, or it returns the LOGIN_FAILED
action.
This way, your Store is always kept in the loop on any side effects, such as HTTP. If one component updates a record in the database, the Effect should notify the Store so that all components subscribed to that data get the updated data.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With