npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ngx-state-manager

v2.0.0

Published

[![npm version](https://badge.fury.io/js/ngx-state-manager.svg)](https://badge.fury.io/js/ngx-state-manager) [![npm downloads](https://img.shields.io/npm/dm/ngx-state-manager.svg)](https://www.npmjs.com/package/ngx-state-manager)

Downloads

24

Readme

ngx-state-manager

npm version npm downloads

Simple state manager based on Angular services.

Table of contents:

Prerequisites

This package depends on Angular v13.0.0.

Getting started

Installation

Install ngx-state-manager from npm:

npm install ngx-state-manager --save

Create state service

Define your state IState and create TodosStateService extended from abstract class FeatureStateManager. The main thing provided by FeatureStateManager is state instance by wich we're gonna manipulate with state changes. You have to define initial state in super method:

interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

interface IState {
  todos: Todo[];
  loaded: boolean;
}

@Injectable({
  providedIn: 'root',
})
export class TodosStateService extends FeatureStateManager<IState> {
  constructor(private http: HttpClient) {
    super({
      todos: [],
      loaded: false,
    });
  }

  getTodos(): Observable<Todo[]> {
    if (!this.state.getValue('loaded')) {
      this.http.get(GET_TODOS_URL).subscribe(todos => {
        this.state.set('todos', todos);
        this.state.set('loaded', true);
      });
    }
    return this.state.get('todos');
  }
}

app.module.ts

Add TodosStateService to your app module using StateManagerModule:

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, StateManagerModule.forRoot([TodosStateService])],
  bootstrap: [AppComponent],
})
export class AppModule {}

state-manager.service.ts

For your convenience create StateManager that gonna include all state services:

@Injectable({ providedIn: 'root' })
export class StateManagerService {
  constructor(
    public todos: TodosStateService,
    public auth: AuthStateService,
    public whatever: MyAnotherStateService
  ) {}
}

app.component.ts

Now you can use StateManager in app component:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  todos$: Observable<Todo[]> = this.stateManager.todos.getTodos();

  constructor(public stateManager: StateManager) {}
}

Events

Besides simple state management library provide events broadcasting mechanism. This mechanism is achived using StateManagerEvents.

For example, you need to clear todos after you've logged out. First of all you need define event:

events.ts

export class LogoutEvent implements StateEvent {
  readonly type = 'LogoutEvent';
}

Then inject StateManagerEvents and use broadcast method with created event as an arguemnt:

auth-state.service.ts

@Injectable({ providedIn: 'root' })
export class AuthStateService extends FeatureStateManager<IState> {
  constructor(private events$: StateManagerEvents) {
    super();
  }

  logout(): void {
    this.state.set('user', null);
    localStorage.removeItem(loggedInKey);
    this.events$.broadcast(new LogoutEvent());
  }
}

To catch event use ListenEvent decorator with appropriate method

todos-state.service.ts

@Injectable({ providedIn: 'root' })
export class TodosStateService extends FeatureStateManager<IState> {
  ...

  @ListenEvent(LogoutEvent)
  clear() {
    this.state.set('todos', []);
    this.state.set('loaded', false);
  }
}

Feature module

You can isolate states and events within particular module using forFeature method of StateManagerModule:

@NgModule({
  imports: [
    BrowserModule,
    StateManagerModule.forFeature([FeatureStateService]),
  ],
  providers: [FeatureStateService],
})
export class MyFeatureModule {}

API

FeatureStateManager has following methods:

  • getState(key: string): Observable<any> get observable of value from state by key
  • getStateValue(key: string): any get current value from state by value (not observable)

State has following methods:

  • get(key: string): Observable<any> get observable of value from state by key
  • set(key: string, value: any): void set value to state using key
  • getValue(key: string): any get current value from state by value (not observable)

StateManagerEvents has following methods:

  • broadcast(value: StateEvent): void broadcast event to all listeners

License

The MIT License (MIT)