>  기사  >  웹 프론트엔드  >  NgRx를 사용하여 각도 상태 관리 마스터하기

NgRx를 사용하여 각도 상태 관리 마스터하기

WBOY
WBOY원래의
2024-09-10 16:30:36421검색

Angular의

상태 관리는 데이터가 애플리케이션의 모든 부분에서 일관되고 효율적으로 공유되도록 보장합니다. 각 구성 요소가 자체 데이터를 관리하는 대신 중앙 저장소가 상태를 유지합니다.

이러한 중앙 집중화를 통해 데이터가 변경되면 모든 구성 요소가 업데이트된 상태를 자동으로 반영하여 일관된 동작과 간단한 코드를 얻을 수 있습니다. 또한 데이터 흐름이 단일 소스에서 관리되므로 앱을 더 쉽게 유지 관리하고 확장할 수 있습니다.

이 기사에서는 간단한 장바구니 애플리케이션을 구축하여 NgRx를 사용하여 Angular에서 상태 관리를 구현하는 방법을 살펴보겠습니다. Store, Actions, Reducers, SelectorsEffects와 같은 NgRx의 핵심 개념을 다루고 이러한 요소들이 어떻게 함께 결합되어 애플리케이션 상태를 관리하는지 보여줍니다. 효과적으로.

Angular의

상태는 장바구니의 콘텐츠와 같이 앱이 관리하고 표시하는 데 필요한 데이터를 나타냅니다.

상태 관리가 필요한 이유

1. 일관성: 모든 구성 요소에서 데이터가 균일하도록 보장합니다. 한 곳에서 데이터가 변경되면 중앙 저장소가 모든 관련 구성 요소를 자동으로 업데이트하여 불일치를 방지합니다.

2. 단순화된 데이터 흐름: 구성 요소 간에 데이터를 수동으로 전달하는 대신 상태 관리를 통해 모든 구성 요소가 중앙 저장소에서 직접 데이터에 액세스하거나 업데이트할 수 있으므로 앱의 데이터 흐름을 더 쉽게 관리하고 이해할 수 있습니다.

3. 간편한 유지 관리 및 확장성: 상태 관리는 데이터 관리를 중앙 집중화하여 코드 중복과 복잡성을 줄입니다. 이렇게 하면 앱이 성장함에 따라 더 쉽게 유지 관리, 디버그 및 확장할 수 있습니다.

4. 성능 최적화: 상태 관리 솔루션에는 전체 애플리케이션을 다시 렌더링하는 대신 상태 변경에 반응해야 하는 구성 요소만 선택적으로 업데이트하는 등 성능을 최적화하는 도구가 함께 제공되는 경우가 많습니다.

NgRx 작동 방식

NgRx는 예측 가능한 방식으로 애플리케이션 상태를 관리하고 유지하는 데 도움이 되는 Angular용 상태 관리 라이브러리입니다.

Mastering Angular State Management using NgRx

1. 구성요소

구성요소는 사용자가 앱과 상호작용하는 곳입니다. 장바구니에 상품을 추가하는 버튼일 수도 있습니다.

구성요소와 서비스가 분리되어 있어 서로 직접적으로 통신하지 않고, 대신 효과 내에서 서비스를 사용하여 기존 Angular 앱과 다른 애플리케이션 구조를 만듭니다.

2. 액션

액션은 발생한 일을 설명하고 필요한 페이로드(데이터)를 포함합니다.

3. 감속기

작업에 따라 상태를 업데이트합니다.

4. 매장

스토어는 애플리케이션의 전체 상태를 보관하는 중앙 집중식 장소입니다.

5. 선택기

스토어에서 부품 데이터를 추출합니다.

6. 효과

효과는 API 호출과 같이 리듀서에 속하지 않는 로직을 처리하는 곳입니다.

7. 서비스

서비스는 실제 비즈니스 로직 또는 API 호출을 수행합니다. Effects는 종종 서비스를 사용하여 서버에서 데이터를 가져오는 등의 작업을 수행합니다.

NgRx를 사용해야 하는 경우

앱의 복잡성으로 인해 정당화되는 경우 NgRx를 사용하세요. 하지만 간단한 앱의 경우 더 간단한 상태 관리 방법을 고수하세요. Angular의 services, signals@Input/@Output 구성요소 간 바인딩은 일반적으로 덜 복잡한 애플리케이션에서 상태를 관리하는 데 충분합니다.

예: NgRx를 사용하여 장바구니에 추가 기능 구축

1.새 Angular 프로젝트 만들기:

ng new shopping-cart

2. NGRX 및 효과 설치
NGRX 및 Effects를 설치하려면 터미널에서 다음 명령을 실행하세요.

ng add @ngrx/store@latest

ng add @ngrx/effects

3. 제품 모델 정의
src/app 디렉터리 내에 product.model.ts

라는 파일을 만듭니다.

제품 구조를 나타내는 제품 인터페이스를 정의합니다.

export interface Product {
    id: string;
    name: string;
    price: number;
    quantity: number;
}

4. 상태 관리 설정
1단계: src/app 디렉토리 내에 상태 폴더 생성

2단계: 장바구니 작업 정의

상태 폴더에 cart.actions.ts를 생성하세요.

import { createActionGroup, emptyProps, props } from '@ngrx/store';
import { Product } from '../product.model';

export const CartActions = createActionGroup({
  source: 'Cart',
  events: {
    'Add Product': props<{ product: Product }>(),
    'Remove Product': props<{ productId: string }>(),
    'Update Quantity': props<{ productId: string; quantity: number }>(),
    'Load Products': emptyProps,
  },
});

export const CartApiActions = createActionGroup({
  source: 'Cart API',
  events: {
    'Load Products Success': props<{ products: Product[] }>(),
    'Load Products Failure': props<{ error: string }>(),
  },
});

3단계: 리듀서 생성

state 폴더에 cart.reducer.ts를 생성하세요.

import { createReducer, on } from '@ngrx/store';
import { Product } from '../product.model';
import { CartActions, CartApiActions } from './cart.actions';

// Initial state for products and cart
export const initialProductsState: ReadonlyArray<Product> = [];
export const initialCartState: ReadonlyArray<Product> = [];

// Reducer for products (fetched from API)
export const productsReducer = createReducer(
  initialProductsState,
  on(CartApiActions.loadProductsSuccess, (_state, { products }) => products)
);

// Reducer for cart (initially empty)
export const cartReducer = createReducer(
  initialCartState,
  on(CartActions.addProduct, (state, { product }) => {
    const existingProduct = state.find(p => p.id === product.id);
    if (existingProduct) {
      return state.map(p =>
        p.id === product.id ? { ...p, quantity: p.quantity + product.quantity } : p
      );
    }
    return [...state, product];
  }),
  on(CartActions.removeProduct, (state, { productId }) =>
    state.filter(p => p.id !== productId)
  ),
  on(CartActions.updateQuantity, (state, { productId, quantity }) =>
    state.map(p =>
      p.id === productId ? { ...p, quantity } : p
    )
  )
);

4단계: 선택기 생성

state 폴더에 cart.selectors.ts
를 생성합니다.

import { createSelector, createFeatureSelector } from '@ngrx/store';
import { Product } from '../product.model';

export const selectProducts = createFeatureSelector<ReadonlyArray<Product>>('products');

export const selectCart = createFeatureSelector<ReadonlyArray<Product>>('cart');

export const selectCartTotal = createSelector(selectCart, (cart) =>
  cart.reduce((total, product) => total + product.price * product.quantity, 0)
);

Step 5: Create Effects

Create a new file cart.effects.ts in the state folder that listens for the Load Products action, uses the service to fetch products, and dispatches either a success or failure action.

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { ProductService } from '../product.service';
import { CartActions, CartApiActions } from './cart.actions';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { of } from 'rxjs';

@Injectable()
export class CartEffects {
  loadProducts$ = createEffect(() =>
    this.actions$.pipe(
      ofType(CartActions.loadProducts),
      mergeMap(() =>
        this.productService.getProducts().pipe(
          map(products => CartApiActions.loadProductsSuccess({ products })),
          catchError(error => of(CartApiActions.loadProductsFailure({ error })))
        )
      )
    )
  );

  constructor(
    private actions$: Actions,
    private productService: ProductService
  ) {}
}

5. Connect the State Management to Your App
In a file called app.config.ts, set up configurations for providing the store and effects to the application.

import { ApplicationConfig } from '@angular/core';
import { provideStore } from '@ngrx/store';
import { provideHttpClient } from '@angular/common/http';
import { cartReducer, productsReducer } from './state/cart.reducer';
import { provideEffects } from '@ngrx/effects';
import { CartEffects } from './state/cart.effects';

export const appConfig: ApplicationConfig = {
  providers: [
    provideStore({
      products: productsReducer, 
      cart: cartReducer 
    }),
    provideHttpClient(),
    provideEffects([CartEffects])
],
};

6. Create a Service to Fetch Products
In the src/app directory create product.service.ts to implement the service to fetch products

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { Product } from './product.model';

@Injectable({ providedIn: 'root' })
export class ProductService {
  getProducts(): Observable<Array<Product>> {
    return of([
      { id: '1', name: 'Product 1', price: 10, quantity: 1 },
      { id: '2', name: 'Product 2', price: 20, quantity: 1 },
    ]);
  }
}

7. Create the Product List Component
Run the following command to generate the component: ng generate component product-list

This component displays the list of products and allows adding them to the cart.

Modify the product-list.component.ts file:

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { Product } from '../product.model';
import { selectProducts } from '../state/cart.selectors';
import { CartActions } from '../state/cart.actions';

@Component({
  selector: 'app-product-list',
  standalone: true,
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css'],
  imports: [CommonModule],
})
export class ProductListComponent implements OnInit {
  products$!: Observable<ReadonlyArray<Product>>;

  constructor(private store: Store) {

  }

  ngOnInit(): void {
    this.store.dispatch(CartActions.loadProducts()); // Dispatch load products action
    this.products$ = this.store.select(selectProducts); // Select products from the store
  }

  onAddToCart(product: Product) {
    this.store.dispatch(CartActions.addProduct({ product }));
  }
}

Modify the product-list.component.html file:

<div *ngIf="products$ | async as products">
  <div class="product-item" *ngFor="let product of products">
    <p>{{product.name}}</p>
    <span>{{product.price | currency}}</span>
    <button (click)="onAddToCart(product)" data-test="add-button">Add to Cart</button>
  </div>
</div>

8. Create the Shopping Cart Component
Run the following command to generate the component: ng generate component shopping-cart

This component displays the products in the cart and allows updating the quantity or removing items from the cart.

Modify the shopping-cart.component.ts file:

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { Product } from '../product.model';
import { selectCart, selectCartTotal } from '../state/cart.selectors';
import { CartActions } from '../state/cart.actions';

@Component({
  selector: 'app-shopping-cart',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './shopping-cart.component.html',
  styleUrls: ['./shopping-cart.component.css'],
})
export class ShoppingCartComponent implements OnInit {
  cart$: Observable<ReadonlyArray<Product>>;
  cartTotal$: Observable<number>;

  constructor(private store: Store) {
    this.cart$ = this.store.select(selectCart);
    this.cartTotal$ = this.store.select(selectCartTotal);
  }

  ngOnInit(): void {}

  onRemoveFromCart(productId: string) {
    this.store.dispatch(CartActions.removeProduct({ productId }));
  }

  onQuantityChange(event: Event, productId: string) {
    const inputElement = event.target as HTMLInputElement;
    let quantity = parseInt(inputElement.value, 10);

    this.store.dispatch(CartActions.updateQuantity({ productId, quantity }));
  }
}

Modify the shopping-cart.component.html file:

<div *ngIf="cart$ | async as cart">
  <div class="cart-item" *ngFor="let product of cart">
    <p>{{product.name}}</p><span>{{product.price | currency}}</span>
    <input type="number" [value]="product.quantity" (input)="onQuantityChange($event, product.id)" />
    <button (click)="onRemoveFromCart(product.id)" data-test="remove-button">Remove</button>
  </div>
  <div class="total">
    Total: {{cartTotal$ | async | currency}}
  </div>
</div>

Modify the shopping-cart.component.css file:

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.cart-item p {
  margin: 0;
  font-size: 16px;
}

.cart-item input {
  width: 50px;
  text-align: center;
}

.total {
  font-weight: bold;
  margin-top: 20px;
}

9. Put Everything Together in the App Component
This component will display the product list and the shopping cart

Modify the app.component.ts file:

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProductListComponent } from './product-list/product-list.component';
import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component';
import { NgIf } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  templateUrl: './app.component.html',
  imports: [CommonModule, ProductListComponent, ShoppingCartComponent, NgIf],
})
export class AppComponent {}

Modify the app.component.html file:

<!-- app.component.html -->
<h2>Products</h2>
<app-product-list></app-product-list>

<h2>Shopping Cart</h2>
<app-shopping-cart></app-shopping-cart>

10. Running the Application
Finally, run your application using ng serve.

Now, you can add products to your cart, remove them, or update their quantities.

Conclusion

In this article, we built a simple shopping cart application to demonstrate the core concepts of NgRx, such as the Store, Actions, Reducers, Selectors, and Effects. This example serves as a foundation for understanding how NgRx works and how it can be applied to more complex applications.

As your Angular projects grow in complexity, leveraging NgRx for state management will help you maintain consistency across your application, reduce the likelihood of bugs, and make your codebase easier to maintain.

To get the code for the above project, click the link below:
https://github.com/anthony-kigotho/shopping-cart

위 내용은 NgRx를 사용하여 각도 상태 관리 마스터하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.