NgRx를 사용하여 각도 상태 관리 마스터하기
Angular의
상태 관리는 데이터가 애플리케이션의 모든 부분에서 일관되고 효율적으로 공유되도록 보장합니다. 각 구성 요소가 자체 데이터를 관리하는 대신 중앙 저장소가 상태를 유지합니다.
이러한 중앙 집중화를 통해 데이터가 변경되면 모든 구성 요소가 업데이트된 상태를 자동으로 반영하여 일관된 동작과 간단한 코드를 얻을 수 있습니다. 또한 데이터 흐름이 단일 소스에서 관리되므로 앱을 더 쉽게 유지 관리하고 확장할 수 있습니다.
이 기사에서는 간단한 장바구니 애플리케이션을 구축하여 NgRx를 사용하여 Angular에서 상태 관리를 구현하는 방법을 살펴보겠습니다. Store, Actions, Reducers, Selectors 및 Effects와 같은 NgRx의 핵심 개념을 다루고 이러한 요소들이 어떻게 함께 결합되어 애플리케이션 상태를 관리하는지 보여줍니다. 효과적으로.
Angular의상태는 장바구니의 콘텐츠와 같이 앱이 관리하고 표시하는 데 필요한 데이터를 나타냅니다.
상태 관리가 필요한 이유
1. 일관성: 모든 구성 요소에서 데이터가 균일하도록 보장합니다. 한 곳에서 데이터가 변경되면 중앙 저장소가 모든 관련 구성 요소를 자동으로 업데이트하여 불일치를 방지합니다.
2. 단순화된 데이터 흐름: 구성 요소 간에 데이터를 수동으로 전달하는 대신 상태 관리를 통해 모든 구성 요소가 중앙 저장소에서 직접 데이터에 액세스하거나 업데이트할 수 있으므로 앱의 데이터 흐름을 더 쉽게 관리하고 이해할 수 있습니다.
3. 간편한 유지 관리 및 확장성: 상태 관리는 데이터 관리를 중앙 집중화하여 코드 중복과 복잡성을 줄입니다. 이렇게 하면 앱이 성장함에 따라 더 쉽게 유지 관리, 디버그 및 확장할 수 있습니다.
4. 성능 최적화: 상태 관리 솔루션에는 전체 애플리케이션을 다시 렌더링하는 대신 상태 변경에 반응해야 하는 구성 요소만 선택적으로 업데이트하는 등 성능을 최적화하는 도구가 함께 제공되는 경우가 많습니다.
NgRx 작동 방식
NgRx는 예측 가능한 방식으로 애플리케이션 상태를 관리하고 유지하는 데 도움이 되는 Angular용 상태 관리 라이브러리입니다.
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

JavaScript는 현대 웹 개발의 핵심 언어이며 다양성과 유연성에 널리 사용됩니다. 1) 프론트 엔드 개발 : DOM 운영 및 최신 프레임 워크 (예 : React, Vue.js, Angular)를 통해 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축합니다. 2) 서버 측 개발 : Node.js는 비 차단 I/O 모델을 사용하여 높은 동시성 및 실시간 응용 프로그램을 처리합니다. 3) 모바일 및 데스크탑 애플리케이션 개발 : 크로스 플랫폼 개발은 개발 효율을 향상시키기 위해 반응 및 전자를 통해 실현됩니다.

이 기사에서는 Contrim에 의해 확보 된 백엔드와의 프론트 엔드 통합을 보여 주며 Next.js를 사용하여 기능적인 Edtech SaaS 응용 프로그램을 구축합니다. Frontend는 UI 가시성을 제어하기 위해 사용자 권한을 가져오고 API가 역할 기반을 준수하도록합니다.

일상적인 기술 도구를 사용하여 기능적 다중 테넌트 SaaS 응용 프로그램 (Edtech 앱)을 구축했으며 동일한 작업을 수행 할 수 있습니다. 먼저, 다중 테넌트 SaaS 응용 프로그램은 무엇입니까? 멀티 테넌트 SAAS 응용 프로그램은 노래에서 여러 고객에게 서비스를 제공 할 수 있습니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.
