Work With NGXS
NGXS is a state management library for Angular applications that offers predictable and efficient state management. It uses actions, reducers, and selectors to handle application state, ensuring immutability and simplifying data flow.
How to use NGXS?
For Product Example:
product.service.ts
constructor(private http: HttpClient) {}
getProducts(payload?: Params): Observable<ProductModel> {
return this.http.get<ProductModel>(`${environment.URL}/product.json`, { params: payload });
}
product.action.ts
import { Params } from "../interface/core.interface";
export class GetProducts {
static readonly type = "[Product] Get";
constructor(public payload?: Params) {}
}
product.state.ts
export class ProductStateModel {
product = {
data: [] as Product[],
total: 0
}
}
@State<ProductStateModel>({
name: "product",
defaults: {
product: {
data: [],
total: 0
},
},
})
@Injectable()
export class ProductState {
constructor( private productService: ProductService ) {}
@Selector()
static product(state: ProductStateModel) {
return state.product;
}
@Action(GetProducts)
getProducts(ctx: StateContext<ProductStateModel>, action: GetProducts) {
return this.productService.getProducts(action.payload).pipe(
tap({
next: (result: ProductModel) => {
ctx.patchState({
product: {
data: result.data,
total: result?.total ? result?.total : result.data?.length
}
});
},
error: err => {
throw new Error(err?.error?.message);
}
})
);
}
}
product.component.ts
import { Component } from '@angular/core';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { ProductModel } from '../../../shared/interface/product.interface';
import { ProductState } from '../../../shared/state/product.state';
@Component({
selector: 'app-collection',
templateUrl: './collection.component.html',
styleUrls: ['./collection.component.scss']
})
export class ProductComponent {
@Select(ProductState.product) product$: Observable<ProductModel>;
constructor(private store: Store){
this.store.dispatch(new GetProducts(this.filter));
}
}