{"id":19273897,"url":"https://github.com/rintoj/angular-reflux","last_synced_at":"2025-10-29T17:04:08.065Z","repository":{"id":57179051,"uuid":"72786430","full_name":"rintoj/angular-reflux","owner":"rintoj","description":"A  uni-directional (flux-like) data flow archicture using immutablity and observables. Clone https://github.com/rintoj/angular-reflux-starter to get started","archived":false,"fork":false,"pushed_at":"2017-05-25T11:12:39.000Z","size":6344,"stargazers_count":8,"open_issues_count":1,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-08T23:37:23.103Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rintoj.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-11-03T21:01:08.000Z","updated_at":"2021-05-14T12:30:48.000Z","dependencies_parsed_at":"2022-09-09T17:31:06.239Z","dependency_job_id":null,"html_url":"https://github.com/rintoj/angular-reflux","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rintoj%2Fangular-reflux","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rintoj%2Fangular-reflux/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rintoj%2Fangular-reflux/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rintoj%2Fangular-reflux/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rintoj","download_url":"https://codeload.github.com/rintoj/angular-reflux/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249775855,"owners_count":21323826,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-09T20:44:24.417Z","updated_at":"2025-10-29T17:04:03.022Z","avatar_url":"https://github.com/rintoj.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n# angular-reflux\nThis module will help you implement a unidirectional data flow (Flux architecture) for an Angular 2 (or above) application in an elegant way. This is inspired by [refluxjs](https://github.com/reflux/refluxjs) and [redux](http://redux.js.org/).\n\n## This project is migrated to [StateX](https://github.com/rintoj/statex)\n**This project is no longer maintained. To know how to migrate to StateX [read this](https://github.com/rintoj/statex#migrating-from-angular-reflux)**\n\n## Update (24 Mar 2017)\n\nSince version `1.0.0`, this module is compatible with Angular's Ahead-of-Time Compilation (AOT). I have updated all examples to reflect this change. If you are here for the first time, never mind, continue reading. But if you have had used this module before and you want to refactor your code to make it AOT compatible check [Making Your Code AOT Compatible](#making-your-code-aot-compatible) section.\n\n## About\n\nFlux is an architecture for unidirectional data flow. By forcing the data to flow in a single direction, Flux makes it easy to reason *how data-changes will affect the application* depending on what actions have been issued. The components themselves may only update  application-wide data by executing an action to avoid double maintenance nightmares.\n\nInspired by redux and refluxjs, I wrote this library to help you implement a unidirectional data flow in 5 simple steps.\n\n## Install\n\n```\nnpm install angular-reflux seamless-immutable --save\n```\n\n## 5 Simple Steps\n\n### 1. Define State\nTo get the best out of TypeScript, declare an interface that defines the structure of the application-state.\n\n```ts\nexport interface Todo {\n  id?: string;\n  title?: string;\n  completed?: boolean;\n}\n\nexport interface State {\n  todos?: Todo[];\n  selectedTodo?: Todo;\n}\n```\n\n### 2. Define Action\nDefine actions as classes with the necessary arguments passed on to the constructor. This way we will benefit from the type checking; never again we will miss-spell an action, miss a required parameter or pass a wrong parameter. Remember to extend the action from `Action` class. This makes your action listenable and dispatch-able.\n\n```ts\nimport { Action } from 'angular-reflux';\n\nexport class AddTodoAction extends Action {\n  constructor(public todo: Todo) { super(); }\n}\n```\n\n### 3. Create Store \u0026 Bind Action\nUse `@BindAction` decorator to bind a reducer function with an Action. The second parameter to the reducer function (`addTodo`) is an action (of type `AddTodoAction`); `@BindAction` uses this information to bind the correct action. Also remember to extend this class from `Store`.\n\n```ts\nimport { Injectable } from '@angular/core';\nimport { BindAction, Store } from 'angular-reflux';\nimport { Observable } from 'rxjs/Observable';\nimport { Observer } from 'rxjs/Observer';\n\n@Injectable()\nexport class TodoStore extends Store {\n\n  @BindAction()\n  addTodo(state: State, action: AddTodoAction): Observable\u003cState\u003e {\n    return Observable.create((observer: Observer\u003cState\u003e) =\u003e {\n      observer.next({ todos: state.todos.concat([action.todo]) });\n      observer.complete();\n    });\n  }\n}\n```\n\nDid you notice `@Injectable()`? Well, stores are injectable modules and uses Angular's dependency injection to instantiate. So take care of adding store to `providers` and to inject into `app.component`. Read [Organizing Stores](#organizing-stores) to understand more.\n\n### 4. Dispatch Action\n\nNo singleton dispatcher! Instead this module lets every action act as dispatcher by itself. One less dependency to define, inject and maintain.\n\n```ts\nnew AddTodoAction({ id: 'sd2wde', title: 'Sample task' }).dispatch();\n```\n\n### 5. Consume Data\n\nUse `@BindData` decorator and a selector function (parameter to the decorator) to get updates from application state. The property gets updated only when the value, returned by the selector function, changes from previous state to the current state. Additionally, just like a map function, you could map the data to another value as you choose.\n\nWe may, at times need to derive additional properties from the data, sometimes using complex calculations. Therefore `@BindData` can be used with functions as well.\n\n```ts\nimport { BindData, DataObserver } from 'angular-reflux';\n\nexport function selectTodos(state: State) {\n  return state.todos;\n}\n\nexport function computeHasTodos(state: State) {\n  return state.todos \u0026\u0026 state.todos.length \u003e 0;\n}\n\n@Component({\n    ....\n})\nexport class TodoListComponent extends DataObserver {\n\n  // mapping a direct value from state\n  @BindData(selectTodos)\n  protected todos: Todo[];\n\n  // mapping a different value from state\n  @BindData(computeHasTodos)\n  protected hasTodos: boolean;\n\n  // works with functions to allow complex calculations\n  @BindData(selectTodos)\n  protected todosDidChange(todos: Todo[]) {\n    // your calculations\n  }\n}\n```\n\n## Making Your Code AOT Compatible\n\nThe selector function to `@BindData()` decorator must be an exported standalone function, to avoid the below AOT error:\n\n```bash\nERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function\n```\n\nTherefore refactor your code from:\n\n```ts\n@Component({\n  ....\n})\nexport class TodoComponent {\n\n  @BindData((state: State) =\u003e state.todos)\n  todos: Todo[]\n}\n```\n\nto:\n\n```ts\nexport function selectTodos(state: State) {\n  return state.todos;\n}\n\n@Component({\n  ....\n})\nexport class TodoComponent extends DataObserver {\n\n  @BindData(selectTodos)\n  todos: Todo[]\n}\n```\n\nRemember to extend your class from `DataObserver`. It is essential to instruct Angular Compiler to keep `ngOnInit` and `ngOnDestroy` life cycle events, which can only be achieved by implementing `OnInit` and `OnDestroy` interfaces. Because of this constraint all components using `@BindData` must extend itself from `DataObserver` which sets `ngOnInit` and `ngOnDestroy` properly; `@BindData` inturn depends on these functions. However if you would like to extend your class from your-own base class you may do so after making sure `ngOnInit` and `ngOnDestroy` are implemented properly.\n\n## Reducer Functions \u0026 Async Tasks\n\nReducer functions can return either of the following\n\n* A portion of the application state as plain object\n```ts\n@BindAction()\nadd(state: State, action: AddTodoAction): State {\n  return {\n    todos: (state.todos || []).concat(action.todo)\n  }\n}\n```\n\n* A portion of the application state wrapped in Promise, if it needs to perform an async task.\n```ts\n@BindAction()\nadd(state: State, action: AddTodoAction): Promise\u003cAppStore\u003e {\n  return new Promise((resolve, reject) =\u003e {\n    asyncTask().then(() =\u003e {\n      resolve({\n        todos: (state.todos || []).concat(action.todo)\n      })\n    })\n  })\n}\n```\n\n* A portion of the application state wrapped in Observables, if the application state needs update multiple times over a period of time, all when handling an action. For example, you have to show loader before starting the process, and hide loader after you have done processing, you may use this.\n```ts\n@BindAction()\nadd(state: State, action: AddTodoAction): Observable\u003cState\u003e {\n  return Observable.create((observer: Observer\u003cState\u003e) =\u003e {\n    observer.next({ showLoader: true })\n    asyncTask().then(() =\u003e {\n      observer.next({\n        todos: (state.todos || []).concat(action.todo),\n        showLoader: false\n      })\n      observer.complete()\n    })\n  })\n}\n```\n\n## Initializing State \u0026 Enabling HotLoad\n\nYou can initialize the app state using the following code.\n\n```ts\n...\nimport { INITIAL_STATE } from './../state'\nimport { environment } from '../environments/environment'\nimport { initialize } from 'angular-reflux'\n\ninitialize(INITIAL_STATE, {\n  hotLoad: !environment.production,\n  domain: 'my-app'\n})\n\n@NgModule({\n  ....\n  bootstrap: [AppComponent]\n})\nexport class AppModule { }\n```\n\nIf you set `hotLoad` to true, every change to the state is preserved in localStorage and re-initialized upon refresh. If a state exists in localStorage `INITIAL_STATE` will be ignored. This is very useful for development builds because developers can return to the same screen after every refresh. Remember the screens must written to react to state (reactive UI) in-order to achieve this. `domain` is an optional string to uniquely identify your application.\n\n## Immutable Application State\nTo take advantage of Angular 2’s change detection strategy — OnPush — we need to ensure that the state is indeed immutable. This module uses [seamless-immutable](https://github.com/rtfeldman/seamless-immutable) for immutability.\n\nSince application state is immutable, the reducer functions will not be able to update  state; any attempt to update the state will result in error. Therefore a reducer function should either return a portion of the state that needs change (recommended) or a new application state wrapped in `ReplaceableState`, instead.\n\n```ts\nexport class TodoStore extends Store {\n\n  @BindAction()\n  selectTodo(state: State, action: SelectTodoAction): Observable\u003cState\u003e {\n    return Observable.create((observer: Observer\u003cState\u003e) =\u003e {\n\n      // returns only the changes\n      observer.next({\n          selectedTodo: action.todo\n      });\n\n      observer.complete();\n    });\n  }\n\n  @BindAction()\n  resetTodos(state: State, action: ResetTodosAction): Observable\u003cState\u003e {\n    return Observable.create((observer: Observer\u003cState\u003e) =\u003e {\n\n      // returns the entire state (use with CAUTION)\n      observer.next(new ReplaceableState({\n        todos: [],\n        selectedTodo: undefined\n      }));\n\n      observer.complete();\n    });\n  }\n}\n```\n\n## Organizing Stores\n\nStore must be injectable, so add `@Injectable`. Create `STORES` array and a class `Stores` (again injectable) to maintain stores. When you create a new store remember to, inject to the `Stores`'s constructor and add it to the `STORES` array.\n\n```ts\nimport { Injectable } from '@angular/core';\nimport { TodoStore } from './todo.store';\n\n@Injectable()\nexport class Stores {\n  constructor( private todoStore: TodoStore) { }\n}\n\nexport const STORES = [\n  Stores,\n  TodoStore\n];\n```\n\nAdd `STORES` to the `providers` in `app.module.ts`.\n\n```ts\nimport { STORES } from './store/todo.store';\n....\n\n@NgModule({\n  ....\n  providers: [\n    ...STORES,\n    ...\n  ],\n  bootstrap: [AppComponent]\n})\nexport class AppModule { }\n\n```\n\nAnd finally, inject `Stores` into your root component (`app.component.ts`)\n\n```ts\n@Component({\n  ....\n})\nexport class AppComponent {\n\n  constructor(private stores: STORES) { }\n\n  ....\n}\n```\n\n## Sample Code\n\nSample code is right [here](https://github.com/rintoj/angular-reflux-starter). You can clone my repo to get started with angular2 project integrated with this module.\n\n```sh\ngit clone https://github.com/rintoj/angular-reflux-starter\n```\n\n### Hope this module is helpful to you. Please make sure to checkout my other [projects](https://github.com/rintoj) and [articles](https://medium.com/@rintoj). Enjoy coding!\n\n## Contributing\nContributions are very welcome! Just send a pull request. Feel free to contact [me](mailto:rintoj@gmail.com) or checkout my [GitHub](https://github.com/rintoj) page.\n\n## Author\n\n**Rinto Jose** (rintoj)\n\nFollow me:\n  [GitHub](https://github.com/rintoj)\n| [Facebook](https://www.facebook.com/rinto.jose)\n| [Twitter](https://twitter.com/rintoj)\n| [Google+](https://plus.google.com/+RintoJoseMankudy)\n| [Youtube](https://youtube.com/+RintoJoseMankudy)\n\n## Versions\n[Check CHANGELOG](https://github.com/rintoj/angular-reflux/blob/master/CHANGELOG.md)\n\n## License\n```\nThe MIT License (MIT)\n\nCopyright (c) 2016 Rinto Jose (rintoj)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frintoj%2Fangular-reflux","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frintoj%2Fangular-reflux","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frintoj%2Fangular-reflux/lists"}