How will my ngrx store detect server side changes?

I recently added ngrx store to my existing angular2 application to simplify code and maintain overall state. However, I got confused in one part, I update my state from the server once at the beginning and after the wards, I just work on the state without checking the server. So what happens when, for example, a thing changes on the backend? Should I check this every time I go to this page or is there a better way? Basically, I want to know what is the best practice to update state data to show server data?

+6
source share
1 answer

Using NGRX Effects is recommended . When you implement NGRX Effects with the Store, any HTTP side effects are handled by effects, which in turn will use the store action to update the data. The effect listens for the action and uses the Action payload to perform the side effect (HTTP). When an Effect ends, it invokes a new action (either an Action for success or an action for failure) with a new payload, thereby updating the data in the Warehouse.

In the example in the Effects Documents, it shows the 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' }))
      );
}

Login. Login , HTTP POST. HTTP POST , LOGIN_SUCCESS json , LOGIN_FAILED.

, , HTTP. , Effect Store, , , .

, .

+4

Source: https://habr.com/ru/post/1015792/


All Articles