Store는 Actions을 dispatch를 듣고, Global State에서 데이터를 select 할 방법을 제공하는 Global State Manager이다
export class Animal {
static readonly type = "[Zoo] Add Animal";
constructor(public name: string) {}
}
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));
}
}
여러 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();
});
}
}
의도적으로 상태를 리셋하고 싶을 경우(unit test, isolated한 테스트...등) store.reset(myNewStateObject)
를 이용한다. (side effect이 존재)