Angular 2 uses observables for many features and has a peer dependency on RxJs for its robust API around observables.

Did you know viralme.io was created with angular2?

The community has adopted a single store approach for dealing with state in modern applications. Let’s build a store for our Angular applications that is both reactive and easy to use with RxJs.

Single store is awesome
We’ll create this store with intentions on it being the only store in our app. By doing this, we can provide a better experience and lower the difficulty of reasoning about state in our app, because all the state is in one place! First we’ll create the provider for the store itself.

export class AppStore {}
Add a subject
Right now our store literally does nothing. We want this store to have a reactive api that we can use in our application. We’re going to create a Subject using RxJs. A subject is perfect for our store because we can multicast to more than one observer. This just means we can setup many listeners. This is going to allow use to subscribe to our store in other components and providers. We need the Subject to always know what the current state is at all times, and when a new observer subscribes, the Subject should provide the observer the current state. Luckily, there is a special Subject for this, a Behavior Subject. Let’s make our store reactive!

import { BehaviorSubject } from ‘rxjs/BehaviorSubject’;

const store = new BehaviorSubject();

export class AppStore {
store = store;
}
Above we created the store outside the class to ensure there will only ever be one instance of the actual store no matter how Angular injects and instantiates the AppStore provider. Now lets set a default value for our store.

import { BehaviorSubject } from ‘rxjs/BehaviorSubject’;

const state = {
user: {},
isLoading: false,
items: []
};

const store = new BehaviorSubject<any>(state);

export class AppStore {
store = store;
}
Subscriptions
At this point, our AppStore is ready to be used in our app! Yea, that’s basically it, surprised? Although we could stop here, we should make it super easy to work with the store in our application.