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
, whereFEATURE
is the part of the application the action pertains to, andACTION
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.