Blog>
Snippets

Akita Entity Store CRUD Operations

Provide code examples that create, read, update, and delete entities in an Akita EntityStore, including Angular service integration.
import { Injectable } from '@angular/core';
import { EntityStore, StoreConfig, EntityState, ID } from '@datorama/akita';

export interface Item extends EntityState {
  id: ID;
  name: string;
  // other properties
}

@Injectable({ providedIn: 'root' })
@StoreConfig({ name: 'items' })
export class ItemStore extends EntityStore<ItemState> {
  constructor() {
    super();
  }
}
Defines an Akita EntityStore for items. It includes an Item interface that outlines the structure of an item entity.
import { Injectable } from '@angular/core';
import { ItemStore } from './item.store';
import { ID } from '@datorama/akita';

@Injectable({ providedIn: 'root' })
export class ItemService {

  constructor(private itemStore: ItemStore) {}

  createItem(item) {
    this.itemStore.add(item);
  }

  getItem(id: ID) {
    return this.itemStore.selectEntity(id);
  }

  updateItem(id: ID, item) {
    this.itemStore.update(id, item);
  }

  deleteItem(id: ID) {
    this.itemStore.remove(id);
  }

  // ... other methods
}
This service utilizes the ItemStore to perform CRUD operations. The service provides methods like createItem, getItem, updateItem, and deleteItem.
<!-- example.component.html -->
<button (click)="createItem()">Add Item</button>
<button (click)="updateItem(1)">Update Item</button>
<button (click)="deleteItem(1)">Delete Item</button>
The HTML template of an Angular component with buttons that trigger the CRUD operations.
// example.component.css
button {
  margin: 5px;
}
The CSS for the component, just providing a basic styling to space out the buttons.
import { Component } from '@angular/core';
import { ItemService } from './item.service';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {
  constructor(private itemService: ItemService) {}

  createItem() {
    const newItem = { id: Date.now(), name: 'New Item' };
    this.itemService.createItem(newItem);
  }

  updateItem(id) {
    const updatedItem = { name: 'Updated Item' };
    this.itemService.updateItem(id, updatedItem);
  }

  deleteItem(id) {
    this.itemService.deleteItem(id);
  }
}
This Angular component implements the UI logic. It calls the corresponding methods in ItemService when buttons are clicked to perform CRUD operations.