AngularJS Store
v4.0.5
v4.0.5
  • Introduction
  • What's New
  • Installation
  • Tutorials with Javascript
    • Setup a store
    • Get the current state
    • Update the state
    • Listen on state changes
    • Destroy a hook
  • Tutorials with Typescript
    • Setup a store
    • Get the current state
    • Update the state
    • Listen on state changes
    • Destroy a hook
Powered by GitBook
On this page

Was this helpful?

  1. Tutorials with Typescript

Setup a store

To create a store, you need to import and use the NgStore class. NgStore accepts a single parameter as the initial state of your store.

counter-store.ts
import NgStore from 'angularjs-store';

const initialState = { count: 0 };
const counterStore = new NgStore(initialState);

That's the simplest way you create a store. If you want to fully type-safe your store, you can populate the NgStore generic parameters. The first generic parameter refers to the type of state. Then the second one refers to the available actions you can use in your store.

counter-store.ts
import NgStore from 'angularjs-store';

type CounterState = { count: 0 };
type CounterActions = ['INCREMENT_COUNT', 'DECREMENT_COUNT'];

const counterStore = new NgStore<CounterState, CounterActions>({ count: 0 });

Finally, to make the store injectable in your AngularJS application, you need to attach it to AngularJS service.

It is recommended to always export the types of store's state, store's actions, and the store itself so you can easily reuse it inside your application.

counter-store.ts
import NgStore from 'angularjs-store';

export type CounterState = { count: number };
export type CounterActions = ['INCREMENT_COUNT', 'DECREMENT_COUNT'];
export type CounterStore = NgStore<CounterState, CounterActions>;

function counterStore() {
  const initialState: CounterState = { count: 0 };
  const counterStore: CounterStore = new NgStore(initialState);
  
  return counterStore;
}

angular
  .module('app', [])
  .service('counterStore', counterStore);
PreviousTutorials with TypescriptNextGet the current state

Last updated 5 years ago

Was this helpful?