Implement an EntityStore for collections
masterTo manage a collection of entities (e.g., a list of products), use EntityStore and QueryEntity.
- Define an
EntityStateinterface that extendsEntityState<T, ID>. - Extend
EntityStore<State>for the store. - Extend
QueryEntity<State>for the query. - Use methods like
.set(),.add(),.update(), and.remove()in your service to manage the collection.
import { Injectable } from '@angular/core';
import { EntityState, EntityStore, StoreConfig, QueryEntity, ID } from '@datorama/akita';
// Model
export interface Product {
id: number;
title: string;
description: string;
price: number;
}
// Store
export interface ProductsState extends EntityState<Product, number> {}
@Injectable({ providedIn: 'root' })
@StoreConfig({ name: 'products' })
export class ProductsStore extends EntityStore<ProductsState> {
constructor() {
super();
}
}
// Query
@Injectable({ providedIn: 'root' })
export class ProductsQuery extends QueryEntity<ProductsState> {
constructor(protected store: ProductsStore) {
super(store);
}
}
// Service
@Injectable({ providedIn: 'root' })
export class ProductsService {
constructor(private productsStore: ProductsStore, private http: HttpClient) {}
get() {
return this.http.get<Product[]>('https://api.com').pipe(
tap((entities) => this.productsStore.set(entities))
);
}
add(product: Product) {
this.productsStore.add(product);
}
update(id: number, product: Partial<Product>) {
this.productsStore.update(id, product);
}
remove(id: ID) {
this.productsStore.remove(id);
}
}