찾다
웹 프론트엔드JS 튜토리얼NgRx를 사용하여 각도 상태 관리 마스터하기

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(),
    'Remove Product': props(),
    'Update Quantity': props(),
    'Load Products': emptyProps,
  },
});

export const CartApiActions = createActionGroup({
  source: 'Cart API',
  events: {
    'Load Products Success': props(),
    'Load Products Failure': props(),
  },
});

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
    )
  )
);
</product></product>

4단계: 선택기 생성

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

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

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

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

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

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>> {
    return of([
      { id: '1', name: 'Product 1', price: 10, quantity: 1 },
      { id: '2', name: 'Product 2', price: 20, quantity: 1 },
    ]);
  }
}
</array>

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>>;

  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 }));
  }
}
</readonlyarray>

Modify the product-list.component.html file:

<div async as products>
  <div class="product-item" product of products>
    <p>{{product.name}}</p>
    <span>{{product.price | currency}}</span>
    <button 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>>;
  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 }));
  }
}
</number></readonlyarray>

Modify the shopping-cart.component.html file:

<div async as cart>
  <div class="cart-item" product of cart>
    <p>{{product.name}}</p>
<span>{{product.price | currency}}</span>
    <input type="number" product.id>
    <button 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 id="Products">Products</h2>
<app-product-list></app-product-list>

<h2 id="Shopping-Cart">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으로 문의하세요.
JavaScript로 문자열 문자를 교체하십시오JavaScript로 문자열 문자를 교체하십시오Mar 11, 2025 am 12:07 AM

JavaScript 문자열 교체 방법 및 FAQ에 대한 자세한 설명 이 기사는 JavaScript에서 문자열 문자를 대체하는 두 가지 방법 인 내부 JavaScript 코드와 웹 페이지의 내부 HTML을 탐색합니다. JavaScript 코드 내부의 문자열을 교체하십시오 가장 직접적인 방법은 대체 () 메소드를 사용하는 것입니다. str = str.replace ( "find", "replace"); 이 메소드는 첫 번째 일치 만 대체합니다. 모든 경기를 교체하려면 정규 표현식을 사용하고 전역 플래그 g를 추가하십시오. str = str.replace (/fi

사용자 정의 Google 검색 API 설정 자습서사용자 정의 Google 검색 API 설정 자습서Mar 04, 2025 am 01:06 AM

이 튜토리얼은 사용자 정의 Google 검색 API를 블로그 또는 웹 사이트에 통합하는 방법을 보여 주며 표준 WordPress 테마 검색 기능보다보다 세련된 검색 경험을 제공합니다. 놀랍게도 쉽습니다! 검색을 Y로 제한 할 수 있습니다

예제 색상 JSON 파일예제 색상 JSON 파일Mar 03, 2025 am 12:35 AM

이 기사 시리즈는 2017 년 중반에 최신 정보와 새로운 예제로 다시 작성되었습니다. 이 JSON 예에서는 JSON 형식을 사용하여 파일에 간단한 값을 저장하는 방법을 살펴 봅니다. 키 값 쌍 표기법을 사용하여 모든 종류를 저장할 수 있습니다.

자신의 Ajax 웹 응용 프로그램을 구축하십시오자신의 Ajax 웹 응용 프로그램을 구축하십시오Mar 09, 2025 am 12:11 AM

그래서 여기 당신은 Ajax라는이 일에 대해 배울 준비가되어 있습니다. 그러나 정확히 무엇입니까? Ajax라는 용어는 역동적이고 대화식 웹 컨텐츠를 만드는 데 사용되는 느슨한 기술 그룹을 나타냅니다. 원래 Jesse J에 의해 만들어진 Ajax라는 용어

10 JQuery Syntax Highlighter10 JQuery Syntax HighlighterMar 02, 2025 am 12:32 AM

코드 프레젠테이션 향상 : 개발자를위한 10 개의 구문 하이 라이터 웹 사이트 나 블로그에서 코드 스 니펫을 공유하는 것은 개발자에게 일반적인 관행입니다. 올바른 구문 형광펜을 선택하면 가독성과 시각적 매력을 크게 향상시킬 수 있습니다. 티

8 멋진 jQuery 페이지 레이아웃 플러그인8 멋진 jQuery 페이지 레이아웃 플러그인Mar 06, 2025 am 12:48 AM

손쉬운 웹 페이지 레이아웃에 대한 jQuery 활용 : 8 에센셜 플러그인 jQuery는 웹 페이지 레이아웃을 크게 단순화합니다. 이 기사는 프로세스를 간소화하는 8 개의 강력한 JQuery 플러그인을 강조합니다. 특히 수동 웹 사이트 생성에 유용합니다.

' this ' 자바 스크립트로?' this ' 자바 스크립트로?Mar 04, 2025 am 01:15 AM

핵심 포인트 JavaScript에서는 일반적으로 메소드를 "소유"하는 객체를 말하지만 함수가 호출되는 방식에 따라 다릅니다. 현재 객체가 없으면 글로벌 객체를 나타냅니다. 웹 브라우저에서는 창으로 표시됩니다. 함수를 호출 할 때 이것은 전역 객체를 유지하지만 객체 생성자 또는 그 메소드를 호출 할 때는 객체의 인스턴스를 나타냅니다. call (), apply () 및 bind ()와 같은 메소드를 사용 하여이 컨텍스트를 변경할 수 있습니다. 이 방법은 주어진이 값과 매개 변수를 사용하여 함수를 호출합니다. JavaScript는 훌륭한 프로그래밍 언어입니다. 몇 년 전,이 문장은있었습니다

10 JavaScript & JQuery MVC 자습서10 JavaScript & JQuery MVC 자습서Mar 02, 2025 am 01:16 AM

이 기사는 JavaScript 및 JQuery Model-View-Controller (MVC) 프레임 워크에 대한 10 개가 넘는 튜토리얼을 선별 한 것으로 새해에 웹 개발 기술을 향상시키는 데 적합합니다. 이 튜토리얼은 Foundatio의 다양한 주제를 다룹니다

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기