」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 NgRx 實體簡化您的 Angular 程式碼

使用 NgRx 實體簡化您的 Angular 程式碼

發佈於2024-11-12
瀏覽:785

Simplify Your Angular Code with NgRx Entities

In the summer, I refreshed my NgRx skills by building a small application to handle my favorite places. During that process, I enjoyed NgRx because I had real control over the state of my app.

One thing that caused a lot of noise was the number of selectors and actions to define for CRUD operations. In my personal project, it wasn't too much trouble, but when I was building a large application with many slices and sections, along with selectors and reducers, the code became harder to maintain.

For example, writing actions for success, error, update, and delete, along with selectors for each operation, increased the complexity and required more testing.

That's where NgRx Entities come in. NgRx Entities reduce boilerplate code, simplify testing, speed up delivery times, and keep the codebase more maintainable. In this article, I'll walk you through refactoring the state management of places in my project using NgRx Entities to simplify CRUD logic.

What and Why NgRx Entities?

Before diving into code, let's first understand what NgRx Entities are and why you should consider using them.

What is @NgRx/Entities

NgRx Entities is an extension of NgRx that simplifies working with data collections. It provides a set of utilities that make it easy to perform operations like adding, updating, and removing entities from the state, as well as selecting entities from the store.

Why Do I Need to Move to NgRx Entities?

When building CRUD operations for collections, manually writing methods in the reducer and creating repetitive selectors for each operation can be tedious and error-prone. NgRx Entities offloads much of this responsibility, reducing the amount of code you need to write and maintain. By minimizing boilerplate code, NgRx Entities helps lower technical debt and simplify state management in larger applications.

How Does It Work?

NgRx Entities provides tools such as EntityState, EntityAdapter, and predefined selectors to streamline working with collections.

EntityState

The EntityState interface is the core of NgRx Entities. It stores the collection of entities using two key properties:

  • ids: an array of entity IDs.

  • entities: a dictionary where each entity is stored by its ID.

interface EntityState {
  ids: string[] | number[];
  entities: { [id: string | id: number]: V };
}

Read more about Entity State

EntityAdapter

The EntityAdapter is created using the createEntityAdapter function. It provides many helper methods for managing entities in the state, such as adding, updating, and removing entities. Additionally, you can configure how the entity is identified and sorted.

export const adapter: EntityAdapter = createEntityAdapter();

The EntityAdapter also allows you to define how entities are identified (selectId) and how the collection should be sorted using the sortComparer.

Read more about EntityAdapter

Now that we understand the basics, let's see how we can refactor the state management of places in our application using NgRx Entities

Setup Project

First, clone the repository from the previous article and switch to the branch that has the basic CRUD setup:

git clone https://github.com/danywalls/start-with-ngrx.git
git checkout crud-ngrx
cd start-with-ngrx

?This article is part of my series on learning NgRx. If you want to follow along, please check it out.

https://www.danywalls.com/understanding-when-and-why-to-implement-ngrx-in-angular

https://www.danywalls.com/how-to-debug-ngrx-using-redux-devtools

https://www.danywalls.com/how-to-implement-actioncreationgroup-in-ngrx

https://www.danywalls.com/how-to-use-ngrx-selectors-in-angular

https://danywalls.com/when-to-use-concatmap-mergemap-switchmap-and-exhaustmap-operators-in-building-a-crud-with-ngrx

https://danywalls.com/handling-router-url-parameters-using-ngrx-router-store

This branch contains the setup where NgRx is already installed, and MockAPI.io is configured for API calls.

Our goal is to use NgRx entities to manage places, refactor actions for CRUD operations, update the reducer to simplify it using adapter operations like adding, updating, and deleting places, use selectors to retrieve the list of places from the store.

Installing NgRx Entities

First, install the project dependencies with npm i, and then add NgRx Entities using schematics by running ng add @ngrx/entity.

npm i
ng add @ngrx/entity

Perfect, we are ready to start our refactor!

Refactoring the State

In the previous version of the project, we manually defined arrays and reducers to manage the state. With NgRx Entities, we let the adapter manage the collection logic for us.

First, open places.state.ts and refactor the PlacesState to extend from EntityState.

export type PlacesState = {
  placeSelected: Place | undefined;
  loading: boolean;
  error: string | undefined;
} & EntityState;

Next, initialize the entity adapter for our Place entity using createEntityAdapter:

const adapter: EntityAdapter = createEntityAdapter();

Finally, replace the manual initialState with the one provided by the adapter using getInitialState:

export const placesInitialState = adapter.getInitialState({
  error: '',
  loading: false,
  placeSelected: undefined,
});

We've refactored the state to use EntityState and initialized the EntityAdapter to handle the list of places automatically.

let's move to update the actions to use NgRx Entities.

Refactoring the Actions

In the previous articles, I manually handled updates and modifications to entities. Now, we will use NgRx Entities to handle partial updates using Update.

In places.actions.ts, we update the Update Place action to use Update, which allows us to modify only part of an entity:

import { Update } from '@ngrx/entity';

export const PlacesPageActions = createActionGroup({
  source: 'Places',
  events: {
    'Load Places': emptyProps(),
    'Add Place': props(),
    'Update Place': props }>(), // Use Update
    'Delete Place': props(),
    'Select Place': props(),
    'UnSelect Place': emptyProps(),
  },
});

Perfect, we updated the actions to work with NgRx Entities, using the Update type to simplify handling updates. It's time to see how this impacts the reducer and refactor it to use the entity adapter methods for operations like adding, updating, and removing places.

Refactoring the Reducer

The reducer is where NgRx Entities really shines. Instead of writing manual logic for adding, updating, and deleting places, we now use methods provided by the entity adapter.

Here’s how we can simplify the reducer:

import { createReducer, on } from '@ngrx/store';
import { adapter, placesInitialState } from './places.state';
import { PlacesApiActions, PlacesPageActions } from './places.actions';

export const placesReducer = createReducer(
  placesInitialState,
  on(PlacesPageActions.loadPlaces, (state) => ({
    ...state,
    loading: true,
  })),
  on(PlacesApiActions.loadSuccess, (state, { places }) => 
    adapter.setAll(places, { ...state, loading: false })
  ),
  on(PlacesApiActions.loadFailure, (state, { message }) => ({
    ...state,
    loading: false,
    error: message,
  })),
  on(PlacesPageActions.addPlace, (state, { place }) =>
    adapter.addOne(place, state)
  ),
  on(PlacesPageActions.updatePlace, (state, { update }) =>
    adapter.updateOne(update, state)
  ),
  on(PlacesPageActions.deletePlace, (state, { id }) =>
    adapter.removeOne(id, state)
  )
);

We’ve used methods like addOne, updateOne, removeOne, and setAll from the adapter to handle entities in the state.

Other useful methods include:

  • addMany: Adds multiple entities.

  • removeMany: Removes multiple entities by ID.

  • upsertOne: Adds or updates an entity based on its existence.

Read more about reducer methods in the EntityAdapter.

With the state, actions, and reducers refactored, we’ll now refactor the selectors to take advantage of NgRx Entities’ predefined selectors.

Refactoring the Selectors

NgRx Entities provides a set of predefined selectors that make querying the store much easier. I will use selectors like selectAll, selectEntities, and selectIds directly from the adapter.

Here’s how we refactor the selectors in places.selectors.ts:

import { createFeatureSelector } from '@ngrx/store';
import { adapter, PlacesState } from './places.state';

const selectPlaceState = createFeatureSelector('places');

const { selectAll, selectEntities, selectIds, selectTotal } = adapter.getSelectors(selectPlaceState);

These built-in selectors significantly reduce the need to manually create selectors for accessing state.

After refactoring the selectors to use the predefined ones, reducing the need to manually define my selectors, it is time to update our form components to reflect these changes and use the new state and actions.

Updating the Form Components

Now that we have the state, actions, and reducers refactored, we need to update the form components to reflect these changes.

For example, in PlaceFormComponent, we can update the save method to use the Update type when saving changes:

import { Component, inject } from '@angular/core';
import { Store } from '@ngrx/store';
import { FormsModule } from '@angular/forms';
import { AsyncPipe } from '@angular/common';
import { selectSelectedPlace } from '../../pages/places/state/places.selectors';
import { PlacesPageActions } from '../../pages/places/state/places.actions';
import { Place } from '../../entities/place.model';

@Component({
  selector: 'app-place-form',
  standalone: true,
  imports: [FormsModule, AsyncPipe],
  templateUrl: './place-form.component.html',
  styleUrls: ['./place-form.component.scss'],
})
export class PlaceFormComponent {
  store = inject(Store);


  placeSelected$ = this.store.select(selectSelectedPlace);

  delete(id: string) {
    this.store.dispatch(PlacesPageActions.deletePlace({ id }));
  }

  save(place: Place, name: string) {
    const update = { id: place.id, changes: { name } }; 
    this.store.dispatch(PlacesPageActions.updatePlace({ update }));
  }
}

We updated our form components to use the new actions and state refactored, lets move , let’s check our effects to ensure they work correctly with NgRx Entities

Refactoring Effects

Finally, I will make the effects work with NgRx Entities, we only need to update the PlacesPageActions.updatePlace pass the correct Update object in the updatePlaceEffect$ effect.

export const updatePlaceEffect$ = createEffect(
  (actions$ = inject(Actions), placesService = inject(PlacesService)) => {
    return actions$.pipe(
      ofType(PlacesPageActions.updatePlace),
      concatMap(({ update }) =>
        placesService.update(update.changes).pipe(
          map((updatedPlace) =>
            PlacesApiActions.updateSuccess({ place: updatedPlace })
          ),
          catchError((error) =>
            of(PlacesApiActions.updateFailure({ message: error })),
          ),
        ),
      ),
    );
  },
  { functional: true },
);

Done! I did our app is working with NgRx Entities and the migration was so easy !, the documentation of ngrx entity is very helpfull and

Conclusion

After moving my code to NgRx Entities, I felt it helped reduce complexity and boilerplate when working with collections. NgRx Entities simplify working with collections and interactions with its large number of methods for most scenarios, eliminating much of the boilerplate code needed for CRUD operations.

I hope this article motivates you to use ngrx-entities when you need to work with collections in ngrx.

  • source code: https://github.com/danywalls/start-with-ngrx/tree/ngrx-entities

Photo by Yonko Kilasi on Unsplash

版本聲明 本文轉載於:https://dev.to/danywalls/simplify-your-angular-code-with-ngrx-entities-1dgn?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-11-16
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1和$array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建構一...
    程式設計 發佈於2024-11-16
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-11-16
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    程式設計 發佈於2024-11-16
  • 為什麼 Visual Studio 2010 中 x86 和 x64 的浮點運算不同?
    為什麼 Visual Studio 2010 中 x86 和 x64 的浮點運算不同?
    x86 與x64 之間的浮點算術差異在Visual Studio 2010 中,x86 與x64 版本之間的浮點算術存在明顯差異當比較某些表達式的值時出現。這種差異體現在以下程式碼:float a = 50.0f; float b = 65.0f; float c = 1.3f; float d =...
    程式設計 發佈於2024-11-15
  • 如何提高帶有通配符的 MySQL LIKE 運算子的效能?
    如何提高帶有通配符的 MySQL LIKE 運算子的效能?
    MySQL LIKE 運算子最佳化MySQL LIKE 運算子最佳化問題:使用萬用字元(例如'%test% ')?答案: 是的,在查詢中使用特定模式時,MySQL 可以最佳化LIKE 運算子的效能。 前綴通配符: 如果您的查詢類似於 foo LIKE 'abc%' 或...
    程式設計 發佈於2024-11-15
  • 如何使用 PHP 透過 POST 向外部網站發送資料?
    如何使用 PHP 透過 POST 向外部網站發送資料?
    在PHP 中透過POST 重新導向並傳送資料在PHP 中,您可能會遇到需要將使用者重新導向到外部的情況網站並透過POST 將資料傳遞到該網站。與 HTML 表單不同,PHP 本身並不支援此行為。 GET 與POST在Web 開發中,有兩種​​主要方法用於從來源發送資料到目的地: GET:資料作為查詢...
    程式設計 發佈於2024-11-15
  • 如何使用 GCC 捕捉 Linux 中的分段錯誤?
    如何使用 GCC 捕捉 Linux 中的分段錯誤?
    捕獲Linux 中的分段錯誤問:我在第三方庫中遇到分段錯誤,但我無法解決根本問題。是否有跨平台或特定於平台的解決方案來使用 gcc 捕獲 Linux 中的這些錯誤? A:Linux 允許將分段錯誤作為異常處理。當程式遇到此類故障時,它會收到 SIGSEGV 訊號。透過設定訊號處理程序,您可以攔截此訊...
    程式設計 發佈於2024-11-15
  • 如何在不建立實例的情況下存取Go結構體的類型?
    如何在不建立實例的情況下存取Go結構體的類型?
    在不創建物理結構的情況下訪問Reflect.Type在Go 中,動態加載問題的解決方案需要訪問結構的類型,而無需物理創建它們。雖然現有的解決方案要求在類型註冊之前建立結構體並清除零,但有一種更有效的方法。 人們可以利用 reflect.TypeOf((*Struct)(nil)).Elem()手術。...
    程式設計 發佈於2024-11-15
  • Java中如何有效率地將整數轉換為位元組數組?
    Java中如何有效率地將整數轉換為位元組數組?
    Java 中整數到位元組數組的高效轉換將整數轉換為位元組數組可用於多種目的,例如網路傳輸或資料儲存。有多種方法可以實現此轉換。 ByteBuffer 類別:一個有效的方法是使用 ByteBuffer 類別。 ByteBuffer 是一個儲存二進位資料並提供各種操作來操縱它的緩衝區。使用 ByteBu...
    程式設計 發佈於2024-11-15
  • 如何在 Go 中按多個欄位對結構體切片進行排序?
    如何在 Go 中按多個欄位對結構體切片進行排序?
    按多個欄位對切片物件進行排序依多個條件排序考慮以下Parent 和Child 結構:type Parent struct { id string children []Child } type Child struct { id string }假設我們有一個帶有...
    程式設計 發佈於2024-11-15
  • Qt 線程與 Python 線程:我應該在 PyQt 應用程式中使用哪個?
    Qt 線程與 Python 線程:我應該在 PyQt 應用程式中使用哪個?
    PyQt 應用程式中的線程:Qt 線程與Python 線程尋求使用PyQt 創建響應式GUI 應用程式的開發人員經常遇到到執行的挑戰長時間運行的任務而不影響UI 的功能。一種解決方案是使用單獨的執行緒來完成這些任務。這就提出了使用 Qt 執行緒還是原生 Python 執行緒模組的問題。 Qt 執行緒...
    程式設計 發佈於2024-11-15
  • 為什麼我的PHP提交按鈕沒有觸發回顯和表格顯示?
    為什麼我的PHP提交按鈕沒有觸發回顯和表格顯示?
    PHP 提交按鈕困境:不可用的回顯和表格您的程式碼打算在點擊「提交」按鈕時顯示回顯和表格在PHP 表單上。但是,您遇到了這些元素仍然隱藏的問題。這是因為您使用 if(isset($_POST['submit'])) 來控制這些元素的顯示,但提交按鈕缺少 name 屬性。 解決方案:提...
    程式設計 發佈於2024-11-15
  • 為什麼我的 @font-face EOT 字型無法在 Internet Explorer 中透過 HTTPS 載入?
    為什麼我的 @font-face EOT 字型無法在 Internet Explorer 中透過 HTTPS 載入?
    @font-face EOT 無法透過HTTPS 載入:解決方案在Internet 中與@font-face EOT 檔案在Internet 中無法透過HTTPS 載入的問題在Explorer 版本7、8 和9 中,使用者發現無論HTTPS 上包含的HTML 頁面的託管狀態如何,問題仍然存在。經過實...
    程式設計 發佈於2024-11-15
  • 為什麼透過 Makefile 運行 Go 程式時出現「權限被拒絕」錯誤?
    為什麼透過 Makefile 運行 Go 程式時出現「權限被拒絕」錯誤?
    權限被拒絕:調查「go run」和Makefile 呼叫之間的差異透過Makefile 執行Go 程式時遇到權限被拒絕錯誤可能會令人困惑。此問題源自於 GNU make 或其 gnulib 元件中的錯誤。根本原因在於系統 PATH 中存在一個名為「go」的目錄,該目錄位於實際 Go 執行檔所在的目錄...
    程式設計 發佈於2024-11-15

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3