[NGXS] Store

CheolHyeon Park·2021년 7월 4일
0

Angular

목록 보기
2/7

Store

Store는 Actions을 dispatch를 듣고, Global State에서 데이터를 select 할 방법을 제공하는 Global State Manager이다

Actions 만들기

export class Animal {
	static readonly type = "[Zoo] Add Animal";
	constructor(public name: string) {}
}

Actions을 dispatch하기

import { Store } from '@ngxs/store';
import { AddAnimal } from './animal.actions';

@Component({ ... })
export class ZooComponent {
  constructor(private store: Store) {}

  addAnimal(name: string) {
    this.store.dispatch(new AddAnimal(name));
  }
}
  • store을 사용할 components/services에 주입하고, dispatch한다.

여러 action들을 동시에 dispatch하고 싶을 때는 array를 이용한다.

this.store.dispatch([new AddAnimal('Panda'), new AddAnimal('Zebra')]);

action후, 이 상태를 받고 싶을 때, @Select 을 이용한다.

import { Store, Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { AddAnimal } from './animal.actions';

@Component({ ... })
export class ZooComponent {

	// select decorator를 이용하여 새로운 animals 상태를 받을 수 있다
  @Select(state => state.animals) animals$: Observable<any>;

  constructor(private store: Store) {}

  addAnimal(name: string) {
    this.store
      .dispatch(new AddAnimal(name))
      .pipe(withLatestFrom(this.animals$))
      .subscribe(([_, animals]) => {
        // do something with animals
        this.form.reset();
      });
  }

}

reset

의도적으로 상태를 리셋하고 싶을 경우(unit test, isolated한 테스트...등) store.reset(myNewStateObject) 를 이용한다. (side effect이 존재)

NGXS 공식문서 참고

profile
나무아래에 앉아, 코딩하는 개발자가 되고 싶은 박철현 블로그입니다.

0개의 댓글