2 ways to render redux state in angular view

TL;DR: Be an OBSERVABLE…

  1. BE AN OBSERVER
    1. In this approach, your component does store.subscribe(person)to OBSERVE the person part of the state.
    2. This person is then shown in the component’s template.
    3. Now, if the person changes in store, because you’re observing it, you’ll get the new person value, which will update the UI
    4. Here you have to manually take care of unsubscribing when the component is destroyed etc.
  2. BE AN OBSERVABLE
    1. In this approach, you don’t subscribe to the store, but instead use selectors  that give you observables of the pieces of state that you’re interested in.
    2. These selectors can be made using reselect, compose etc. helper functions
    3. The selector can also be store.select()
    4. Now, your componenent doesn’t have to do anything, coz this selector function is directly bound to the UI with the |async pipe.
    5. async pipe takes care of subscribing to this selector and auto unsubscribing when component is destroyed.
    6. This approach is much more cleaner that previous one.

 

SAMPLE SCENARIO

  • Let’s say we have a object in store that contains a list of values. To display this list in HTML, we’ll use select (to get the observable) and the async pipe (to auto subs to the observable)
    • this.test = this._store.select(val => val.items.items); 
    • <li *ngFor="let item of(test | async)">
      Here is {{item.name}}
      </li>
  • Now, when the user selects a checkbox next to any item, we can store that item in new array, and when user clicks apply, the this new array can be dispatched to the reducer that then updates the item in store.
  • Now, coz the test observable will spit out the new value of the items array and hence UI will be automatically in sync with the store.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s