Angular

Angular - ngrx in State (1) Store

인어공쭈 2023. 3. 7. 16:37

* why use Store?

 

사용하는 이유?

- 상태관리를 제공

 

언제 사용해야될까?

  • 사용자 상호작용이 많고 여러 데이터 소스를 공유할때
  • 외부 저장소에서 유지될때
  • 다른소스의 작업에 영향을 받을때

단점?

- 코드가 짧거나 빠른 방법은 아니다. 또한 많은 파일을 사용하게 된다.

 

 

< 주요 개념 >

Type Safety

- 아키텍처 전제에 타입스크립트를 사용해서 엄격한 형식으로 안전성이 높고 패턴 사용으로 더 높은 품질의 코드가 생성된다.

Immutability and Performance

- 변경할수 없는 단일 데이터 구조를 기반으로 구축되어 비교적 간단한 작업 가능

Encapsulation

- 외부 리소스 사용으로 인한 부작용에서 격리시킬수 있다.

Serializability

- 직렬화 가능성을 제공하고 이를 통해 외부 저장소에 저장도 가능 (localStorage)

Testable

- 격리된 기능을 사용하기 때문에 테스트가 간단해진다.

 

 

* Getting Started

 

< 주요 개념 >

- RxJS 기반 글로벌 상태 관리

- 상태 변경은 새 상태를 계산하기 위해 현재 상태와 최신 작업을 하는 Reducer에 의해 처리

- 설치방법은 아래 참고

https://ngrx.io/guide/store/install

 

Diagram

 

* Architecture

 

Actions

- 시스템의 입력 및 출력

- 상태를 변경하는 데 사용되는 객체

- Actions 객체를 처리하는 Reducer 함수가 호출되어 새로운 상태 객체가 생성되고, 이 상태 객체가 Store에 저장된다

import { createAction, props } from '@ngrx/store';

export const login = createAction(
  '[Login Page] Login',
  props<{ username: string; password: string }>()
);

 

reducers

- 상태를 정의하는 인터페이스 또는 유형

- 주어진 입력에 대해 동일한 출력을 생성한다

- 작업에 대한 상태 변경을 처리하는 함수

import { Action, createReducer, on } from '@ngrx/store';
import * as ScoreboardPageActions from '../actions/scoreboard-page.actions';

export interface State {
  home: number;
  away: number;
}

 

selectors

- (state)에서 필요한 데이터를 추출하거나 변환하는 함수

- 접근을 캡슐화, 컴포넌트에서는 selector를 호출하여 필요한 데이터만 가져올 수 있다

import { createSelector } from '@ngrx/store';
 
export interface FeatureState {
  counter: number;
}
 
export interface AppState {
  feature: FeatureState;
}
 
export const selectFeature = (state: AppState) => state.feature;
 
export const selectFeatureCount = createSelector(
  selectFeature,
  (state: FeatureState) => state.counter
);

 

 

meta Reducer

 

- Reducer 함수와 유사하게 동작

- 여러 개의 함수를 연결하여 사용할 수 있으며, 실행 순서도 정의할 수 있다

- 애플리케이션의 모든 상태 변화를 감지

import { StoreModule, ActionReducer, MetaReducer } from '@ngrx/store';
import { reducers } from './reducers';

// console.log all actions
export function debug(reducer: ActionReducer<any>): ActionReducer<any> {
  return function(state, action) {
    console.log('state', state);
    console.log('action', action);

    return reducer(state, action);
  };
}

export const metaReducers: MetaReducer<any>[] = [debug];

@NgModule({
  imports: [
    StoreModule.forRoot(reducers, { metaReducers })
  ],
})
export class AppModule {}

 

Action groups

- 여러 개의 액션을 그룹화 하는 기능

import { createActionGroup, emptyProps, props } from '@ngrx/store';
 
export const ProductsPageActions = createActionGroup({
  source: 'Products Page',
  events: {
    // defining an event without payload using the `emptyProps` function
    'Opened': emptyProps(),
    
    // defining an event with payload using the `props` function
    'Pagination Changed': props<{ page: number; offset: number }>(),
    
    // defining an event with payload using the props factory
    'Query Changed': (query: string) => ({ query }),
  }
});

 

반응형

'Angular' 카테고리의 다른 글

Angular - 타입스크립트의 장점  (0) 2023.03.20
Angular 란?  (0) 2023.03.14
Angular - NgRx란?  (0) 2023.03.08
Angular - ngrx in State (3) router-store&Entity& component-store  (0) 2023.03.08
Angular - ngrx in State (2) Effects  (0) 2023.03.08