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

/**
* CONSTANT
* @type {string}
*/
export const GET_CATEGORIES = "GET_CATEGORIES"; /**
* INIT VALUE
*/
export const initialCategories = [
{id: , name: 'Development'},
{id: , name: 'Design'},
{id: , name: 'Exercise'},
{id: , name: 'Humor'}
]; /**
* REDUCERS
* @type {string}
*/
export const categories = (state = initialCategories, {type, payload}) => {
switch(type) {
case GET_CATEGORIES:
return payload || state;
default:
return state;
}
};

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

Then let's create a gloable store for the app, which has two methods, getState, dispatch.  Two props: reducer, state.

class Store {
constructor(reducer, initialState) {
this.reducer = reducer;
this.state= initialState;
} getState() {
return this.state
} dispatch() {
this.state = this.reducer(this.state, action);
} }

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

import {categories, initialCategories} from './components/categories/category.state';
import Store from './app.store';
const store = new Store(categories, initialCategories);

We passed in categoreis reudcer and the initialCategories state.

To make 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.categories = this.store.getState();
}
}

Now we are going to simply the code a little bit, we going to make a subscribe method so that we don't need to call getState() method everytime after we dispatch an action.

You can think that the subscribe method is a just callback function which each time we dispatch an action, it will be called. And inside the callback function, we will call this.store.getState() to get the value.

class Store {
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);
}
}
} export default Store;
class CategoriesController {
constructor($timeout, store) {
'ngInject'; angular.extend(this, {
$timeout,
store
});
} $onInit() {
this.unsubscribe = this.store.subscribe(() => {
this.categories = this.store.getState();
}); this.store.dispatch({type: GET_CATEGORIES});
}
}

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

/**
* ACTIONS CREATOR
*/
export const CategoriesActions = () => {
const getCategoreis = (categories) => {
return {type: GET_CATEGORIES, payload: categories}
}; const getCurrentCategory = (currentCategory) => {
return {type: GET_CURRENT_CATEGORY, payload: currentCategory}
}; return {
getCategoreis,
getCurrentCategory
};
};

To make 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'; angular.extend(this, {
$timeout,
store,
CategoriesActions
});
}
  $onInit() {
this.unsubscribe = this.store.subscribe(() => {
this.categories = this.store.getState();
}); this.store.dispatch(this.CategoriesActions.getCategoreis());
}
  onCategorySelected(currentCategory) {
this.currentCategory = category(this.currentCategory, this.CategoriesActions.getCurrentCategory(currentCategory));
}

[AngularJS] Write a simple Redux store in AngularJS app的更多相关文章

  1. [后端人员耍前端系列]AngularJs篇:30分钟快速掌握AngularJs

    一.前言 对于前端系列,自然少不了AngularJs的介绍了.在前面文章中,我们介绍了如何使用KnockoutJs来打造一个单页面程序,后面一篇文章将介绍如何使用AngularJs的开发一个单页面应用 ...

  2. Angularjs,WebAPI 搭建一个简易权限管理系统 —— Angularjs 前端主体结构(五)

    目录 前言 Angularjs名词与概念 Angularjs 基本功能演示 系统业务与实现 WebAPI项目主体结构 Angularjs 前端主体结构 6 Angularjs 前端主体结构 6.1 A ...

  3. Angularjs,WebAPI 搭建一个简易权限管理系统 —— Angularjs名词与概念(一)

    目录 前言 Angularjs名词与概念 Angularjs 基本功能演示 系统业务与实现 WebAPI项目主体结构 Angularjs 前端主体结构 2. 前言 Angularjs开发CRUD类型的 ...

  4. 【js类库AngularJs】web前端的mvc框架angularjs之hello world

    AngularJS诞生于2009年,由Misko Hevery 等人创建,后为Google所收购.是一款优秀的前端JS框架,已经被用于Google的多款产品当中.AngularJS有着诸多特性,最为核 ...

  5. [Redux] Store Methods: getState(), dispatch(), and subscribe()

    console.clear(); const counter = (state = 0, action) => { switch (action.type) { case 'INCREMENT' ...

  6. [Functional Programming ADT] Create a Redux Store for Use with a State ADT Based Reducer

    With a well defined demarcation point between Redux and our State ADT based model, hooking up to a R ...

  7. [Redux-Observable && Unit Testing] Use tests to verify updates to the Redux store (rxjs scheduler)

    In certain situations, you care more about the final state of the redux store than you do about the ...

  8. Simple Redux

    This is a post that tries to explain the the basics of Redux. We’ll build a minimal working example ...

  9. iOS App Store上架新APP与更新APP版本

    iOS App Store上架新APP与更新APP版本 http://www.jianshu.com/p/9e8d1edca148

随机推荐

  1. css--两行显示省略号兼容火狐浏览器

    css--两行显示省略号兼容火狐浏览器 正常写法: .ellipse1{overflow: hidden;white-space: nowrap;text-overflow: ellipsis;} . ...

  2. linux 下find---xargs以及find--- -exec结合使用

    例:删除/home/raven下,包括子目录里所有名为abc.txt的文件: find /home/raven -name abc.txt | xargs rm -rf 如果不使用xargs,则为: ...

  3. mv---移动文件或目录

    mv命令用来对文件或目录重新命名,或者将文件从一个目录移到另一个目录中.source表示源文件或目录,target表示目标文件或目录.如果将一个文件移到一个已经存在的目标文件中,则目标文件的内容将被覆 ...

  4. 03011_预处理对象executeUpdate方法(实现数据库的增、删、改)

    1.概述 (1)通过预处理对象的executeUpdate方法,完成记录的insert\update\delete语句的执行: (2)操作格式统一如下: ①注册驱动: ②获取连接: ③获取预处理对象: ...

  5. x264代码剖析(八):encode()函数之x264_encoder_close()函数

    x264代码剖析(八):encode()函数之x264_encoder_close()函数 encode()函数是x264的主干函数.主要包含x264_encoder_open()函数.x264_en ...

  6. 9.Maven之(九)依赖关系

    转自:https://yq.aliyun.com/ziliao/312160 在maven的管理体系中,各个项目组成了一个复杂的关系网,但是每个项目都是平等的,是个没有贵贱高低,众生平等的世界,全球每 ...

  7. python路径找类并获取静态字段

    Python通过路径找类并获取其中大写的静态字段 settings.py class Foo: DEBUG = True TEST = True xx.py import importlib path ...

  8. 10. LCD驱动程序 ——框架分析

    引言: 由LCD的硬件原理及操作(可参看韦哥博客:第017课 LCD原理详解及裸机程序分析) 我们知道只要LCD控制器的相关寄存器正确配置好,就可以在LCD面板上显示framebuffer中的内容. ...

  9. JSP页面开发规范案例

    添加 <%@ page language="java" contentType="text/html; charset=utf-8" pageEncodi ...

  10. 【SonicUI】关于字体高亮的问题。。

    m_pSonicString[1]->Format(_T("/c=%x, a='http://hi.csdn.net/', linkh=0xFF00F0, font, font_hei ...