Giter Club home page Giter Club logo

ngrx-store's Introduction

@ngrx/store

Join the chat at https://gitter.im/ngrx/store CircleCI Status for ngrx/store npm version

RxJS powered state management inspired by Redux for Angular 2 apps

Demo

http://plnkr.co/edit/Hb4pJP3jGtOp6b7JubzS?p=preview

Example Application

https://github.com/ngrx/example-app

Introduction

Installation

Make sure you have @angular/core and @ngrx/core installed via npm:

npm install @angular/core @ngrx/core --save

Install @ngrx/store from npm:

npm install @ngrx/store --save

Set up with Angular-CLI and SystemJS. Modify system-config.ts:

    /** Map relative paths to URLs. */
    const map: any = {
        '@ngrx': 'vendor/@ngrx'
    };
    
    /** User packages configuration. */
    const packages: any = {
        '@ngrx/core': {
            main: 'index.js',
            format: 'cjs'
        },
        '@ngrx/store': {
            main: 'index.js',
            format: 'cjs'
        }
    };

Modify angular-cli-build.js by adding this line to vendorNpmFiles:

    '@ngrx/**/*.+(js|js.map)'

Usage

Create a reducer function for each data type you have in your application. The combination of these reducers will make up your application state:

// counter.ts
import { ActionReducer, Action } from '@ngrx/store';

export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const RESET = 'RESET';

export const counterReducer: ActionReducer<number> = (state: number = 0, action: Action) => {
	switch (action.type) {
		case INCREMENT:
			return state + 1;

		case DECREMENT:
			return state - 1;

		case RESET:
			return 0;

		default:
			return state;
	}
}

In your app's main module, import those reducers and use the StoreModule.provideStore(reducers, initialState) function to provide them to Angular's injector:

import { Store, StoreModule } from '@ngrx/store';
import { counterReducer } from './counter';
import { NgModule } from '@angular/core'

@NgModule({
  imports: [
    BrowserModule,
    StoreModule.provideStore({ counter: counterReducer }, { counter: 0 })
  ]
})
export class MyAppModule {}

You can then inject the Store service into your components and services. The store.select method can be used to obtain the appropriate slice(s) of state from your application store:

import { Store } from '@ngrx/store';
import { INCREMENT, DECREMENT, RESET } from './counter';

interface AppState {
  counter: number;
}

@Component({
	selector: 'my-app',
	template: `
		<button (click)="increment()">Increment</button>
		<div>Current Count: {{ counter | async }}</div>
		<button (click)="decrement()">Decrement</button>
	`
})
class MyApp {
	counter: Observable<number>;

	constructor(public store: Store<AppState>){
		this.counter = store.select('counter');
	}

	increment(){
		this.store.dispatch({ type: INCREMENT });
	}

	decrement(){
		this.store.dispatch({ type: DECREMENT });
	}

	reset(){
		this.store.dispatch({ type: RESET });
	}
}

Migrating from Store v1.x

Middleware

The middleware APIs have been removed. There are no plans to reintroduce these APIs and there is not a straightforward upgrade process if you rely on middleware.

Some popular middleware libraries have already been upgraded. If you were using store-saga, checkout @ngrx/effects. If you were using ngrx-store-logger, it has been reimplemented as a meta reducer.

getState(), getValue(), and value

The APIs for synchronously pulling the most recent state value out of Store have been removed. Instead, you can always rely on subscribe() running synchronously if you have to get the state value:

import 'rxjs/add/operator/take';

function getState(store: Store<State>): State {
	let state: State;

	store.take(1).subscribe(s => state = s);

	return state;
}

Contributing

Please read contributing guidelines here.

ngrx-store's People

Contributors

btroncone avatar cschiavolini avatar edd avatar gitter-badger avatar kinggolf avatar mattma avatar meenie avatar mikehaas763 avatar mikeryandev avatar nathanwalker avatar robwormald avatar shprink avatar wesleycho avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.