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

ng-control

v0.0.41

Published

`ngControl` is an intuitive and easy-to-use state manager for Angular applications. It provides a simple interface for managing application state, integrates with Redux DevTools.

Downloads

22

Readme

NgControll

ngControl is an intuitive and easy-to-use state manager for Angular applications. It provides a simple interface for managing application state, integrates with Redux DevTools.

Features

  • Simple and intuitive API
  • Integration with Redux DevTools
  • Type-safe with TypeScript
  • Use Signals

Installation

install the library using npm:

npm i ng-control

Why Use ngControl?

  • Simplicity: ngControl offers an intuitive and simple API for managing application state.
  • Modularity: ngControl is modular and can be easily extended.
  • Integration with Redux DevTools: ngControl supports Redux DevTools, making state debugging easier.
  • Type-safe with TypeScript: ngControl is written in TypeScript, providing type safety and better integration with the Angular ecosystem.

API

Store<T>

Methods

  • getState(): Signal: Returns a signal containing the current state.

  • setState(newState: Partial, action: string = 'SET_STATE'): void: Updates the state and sends the action to Redux DevTools.

  • selectOn(key: K): T[K] | null: Returns the value for the given state key.

  • select(selector: (state:T) => K): K Returns the signal value.

Basic usage

Add Store to you Angular module and configure the initial state.

import {NG_CONTROL_STATE, Store} from "../state/store";

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    { provide: NG_CONTROL_STATE, useValue: { /* initial state can be anything or empty Object */ } },
    Store
  ]
};

Create store interface

interface myStoreInterface {
  firstName: string,
  lastName: string,
}

Usage in a component

export class AppComponent implements OnInit{

  public storeData: myStoreInterface;

  constructor(private store: Store<myStoreInterface>) {
        this.storeData = this.store.getState();
  }
}

Using Actions

Actions are objects that describe the type of change to be made to the application's state. Each action should have a unique name that clearly indicates the type of operation being performed.

Why Use Actions?

  • Track State Changes: Actions allow you to precisely track state changes, which is particularly useful when debugging and using tools like Redux DevTools.
  • Better Code Organization: Using actions helps in organizing your code better and separating business logic from presentation logic.
  • Readability and Clarity: Well-named actions make it easier to understand what is happening in the application.

Creating Actions

  • Action Names: Action names should be descriptive and clearly indicate what they do. A good pattern is to use the format FEATURE_ACTION, where FEATURE is the part of the application the action pertains to, and ACTION describes the operation.
  • Constants: Use constants to define action names to avoid typos and facilitate refactoring.

Using Actions in Methods

public setFirstName(userName: string): void {
  this.store.setState({ firstName: userName },' SET_FIRST_NAME');
}

public changeFirstName(newName: string): void {
  this.store.setState({ firstName: newName }, 'UPDATE_FIRST_NAME');
}

public setUserData(user: myStoreInterface): void {
  this.store.setState ({
    firstName: 'Mateusz',
    lastName: 'Jaracz',
  },'SET_USER_DATA')
}

Get data from store

getState()

  this.store.getState();
  //returns   {firstName: 'Mateusz', lastName: 'Jaracz'}

select()

  this.store.select(state => state.firstName);
  //returns Mateusz

selectOn()

this.store.selectOn('firstName');
//returns Mateusz

Using effect

The effect method performs an HTTP request and updates the state with the response, returning a signal.

Parameters

url: The URL to which the HTTP request is sent.
action: A string describing the action.
method: The HTTP method (GET, POST, PUT, DELETE).
body: (Optional) The request payload.
headers: (Optional) The request headers.

Example

public loadData(): void {
   const headers = new HttpHeaders({
   'Authorization': 'Bearer your-token'
    });
  
   const data: Signal<{ data: T } | null> = this.store.effect<{ data: T }>('https://api.example.com/data', 'LOAD_DATA', 'GET', null, headers);
  
   effect(() => {
      console.log(data());
      // handle data or update component state
  });
}

Using effectObservable

The effectObservable method performs an HTTP request and updates the state with the response, returning an observable.

Parameters

url: The URL to which the HTTP request is sent.
action: A string describing the action.
method: The HTTP method (GET, POST, PUT, DELETE).
body: (Optional) The request payload.
headers: (Optional) The request headers.

Example

public loadData(): void {
    const headers = new HttpHeaders({
      'Authorization': 'Bearer your-token'
    });

    this.store.effectObservable<{ data: T }>('https://api.example.com/data', 'LOAD_DATA', 'GET', null, headers)
    .subscribe(response => {
        console.log(response);
        // handle response or update component state
    });
}

Using auto hydration data

ngControl provides automatic state saving and loading functionality when the browser window is closed. To enable automatic state persistence, configure the provider as follows:

{ provide: 'HYDRATION_KEY', useValue: 'your_key' }.

Once this key is set, ngControl will automatically start saving the specified state values.

For example, if your state structure looks like this:`

{ user: UserInterface, data: DataInterface }`

and you want to automatically save the latest state of the user in the core part of the application, you simply call

`this.store.hydrationData(['user'])`.

This will ensure that the user state is automatically saved and restored when the application is reopened.

Manual clear hydration data

this.store.clearHydrationData();

License ngControl is available under the MIT License. See the LICENSE file for more information.