17.10.2018 Views

Angular

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 41: ngrx<br />

Ngrx is a powerful library that you can use with <strong>Angular</strong>2. The idea behind is to merge two concepts that plays well<br />

together to have a reactive app with a predictable state container : - [Redux][1] - [RxJs][2] The main advantages : -<br />

Sharing data in your app between your components is going to easier - Testing your app core logic consists to test<br />

pure functions, without any dependency on <strong>Angular</strong>2 (very easy so !) [1]: http://redux.js.org [2]:<br />

http://reactivex.io/rxjs<br />

Section 41.1: Complete example : Login/logout a user<br />

Prerequisites<br />

This topic is not about Redux and/or Ngrx :<br />

You need to be comfortable with Redux<br />

At least understand the basics of RxJs and Observable pattern<br />

First, let's define an example from the very beginning and play with some code :<br />

As a developer, I want to :<br />

1.<br />

2.<br />

3.<br />

4.<br />

5.<br />

6.<br />

Have an IUser interface that defines the properties of a User<br />

Declare the actions that we'll use later to manipulate the User in the Store<br />

Define the initial state of the UserReducer<br />

Create the reducer UserReducer<br />

Import our UserReducer into our main module to build the Store<br />

Use data from the Store to display information in our view<br />

Spoiler alert : If you want to try the demo right away or read the code before we even get started, here's a Plunkr<br />

(embed view or run view).<br />

1) Define IUser interface<br />

I like to split my interfaces in two parts :<br />

The properties we'll get from a server<br />

The properties we define only for the UI (should a button be spinning for example)<br />

And here's the interface IUser we'll be using :<br />

user.interface.ts<br />

export interface IUser {<br />

// from server<br />

username: string;<br />

email: string;<br />

// for UI<br />

isConnecting: boolean;<br />

isConnected: boolean;<br />

};<br />

2) Declare the actions to manipulate the User<br />

GoalKicker.com – <strong>Angular</strong> 2 Notes for Professionals 147

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!