[AngularJS] Write a simple Redux store in AngularJS app

Source: Internet
Author: User

The first things we need to does is create a reducer:

/** * CONSTANT * @type {string}*/ExportConstGet_categories ="get_categories";/** * INIT VALUE*/ExportConstInitialcategories =[{ID:0, Name:'Development'}, {ID:1, Name:'Design'}, {ID:2, Name:'Exercise'}, {ID:3, Name:'Humor'}];/** * reducers * @type {string}*/ExportConstCategories = (state = initialcategories, {type, payload}) = = {  Switch(type) { Caseget_categories:returnPayload | |State ; default:      returnState ; }};

It has some default initialize data. What it does are just simply return the state.

Then let's create a gloable store for the app, which have both methods, getState, dispatch. Props: Reducer, state .

class Store {  constructor (reducer, initialstate) {    this. Reducer = reducer;      this. state=  initialstate;  }  GetState () {     returnthis. State  }  Dispatch () {     this  this. Reducer (the. State, action);  }}

Once we got that, we is going to init our store:

 from ' ./components/categories/category.state '  from'./app.store'; Const New Store (categories, initialcategories);

We passed in Categoreis Reudcer and the initialcategories state.

To the IT available to Angular APP. We need to make it injectable:

Let Appmodule = Angular.module ('app', [    commonmodule.name,    Componentsmodule.name     . Value (' store ', store)

Then we can use it in our app:

class Categoriescontroller {  Constructor (store) {    'nginject';    Angular.extend (this, {      store    });  }  $onInit () {    this. Store.dispatch ({type:get_categories});      This  This . Store.getstate ();  }}

Now we're going to simply the code a little bit and we going to make a subscribe method so that we don ' t n Eed to call getState () method Everytime after we dispatch an action.

You can think that the subscribe method are a just callback function which each time we dispatch An action, it'll be called. And inside the callback function, we'll call This.store.getState () to get the value.

classStore {Constructor (reducer, initialstate) { This. Reducer =Reducer;  This. State =initialstate;  This. Listeners = []; } getState () {return  This. State; } dispatch (action) { This. State = This. Reducer ( This. State, action);  This. Listeners.foreach ((L) =l ()); } subscribe (listener) { This. Listeners = [      ... This. Listeners, listener]; //return an unsubscribe function    return() = {       This. Listeners = This. listeners.filter (L = l!==listener); }}}exportdefaultStore;
class Categoriescontroller {  constructor ($timeout, store) {    'nginject';    Angular.extend (this, {      $timeout,      store    });  }  $onInit () {    this. Store.subscribe () =        {this  This . Store.getstate ();    });      This . Store.dispatch ({type:get_categories});}  }

Currently inside the Dispatch () Metod, we pass in a object with type and payload. It would is better if we can manage those action in a single place. There is where Action creator comes on to play.

/**  /  const Categoriesactions = () = = (const ) Getcategoreis = (categories) = {    return  {type:get_categories, payload:categories}< c12/>};   const getcurrentcategory = (currentcategory) = =    {return  {type:get_ Current_category, payload:currentcategory}  };   return {    Getcategoreis,    getcurrentcategory  };};

To the IT avaiable to Angular App, we can create a factory for this:

Let Appmodule = Angular.module ('app', [    commonmodule.name,    Componentsmodule.name  ])    . Value ('store', store).     Factory (' categoriesactions ', categoriesactions)  . Component ( ' app ', AppComponent)

Then we can use it inside the controller:

  constructor ($timeout, store, categoriesactions ) {  " nginject   '  
  $onInit () { this . Unsubscribe = Span style= "color: #0000ff;" >this . Store.subscribe (() => { this
    .categories = this  .store.getstate ();    });  this   .  Categoriesactions.getcategoreis ());  }
  oncategoryselected (currentcategory) {    this. currentcategory = Category ( this  This . Categoriesactions.getcurrentcategory (currentcategory));  }

[AngularJS] Write a simple Redux store in AngularJS app

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.