LoginSignup
0
0

More than 3 years have passed since last update.

Angularの状態管理ライブラリNgxsについて簡単にまとめます

Posted at

先日、Vue.jsの状態管理ライブラリであるVuexの記事を書きました。

この流れでAngularのまとめもしてみようと思います。

NgXs4つの概念

  • Store...Stateの状態などActionの呼び出しや状態のSelectも行う。グローバルコンテナ
  • Actions...状態を変化させるActionとそのメタデータを定義するクラス
  • State...状態を定義するクラス
  • Selects...状態の特定の断面を取り出す関数

Actionの定義

Ngxsの公式サイトのサンプルコードを見ながら理解を深めて行きたいと思います。

以下は
Animalを追加するActionを定義しています。

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

Actionの呼び出し

ZooComponent内で先程定義したAddAnimalを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));
  }
}

また、以下のように記述することで、複数のActionを同時にdispatchすることができます。

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

Stateの定義

import { Injectable } from '@angular/core';
import { State, Action, StateContext } from '@ngxs/store';

export class FeedAnimals {
  static readonly type = '[Zoo] FeedAnimals';
}

export interface ZooStateModel {
  feed: boolean;
}

@State<ZooStateModel>({
  name: 'zoo',
  defaults: {
    feed: false
  }
})

@Stateデコレータにより、Sstateクラスであることを宣言し、引数として渡されたZooStateModelのデータを保持します。

Component({ ... })
export class ZooComponent {
  // Reads the name of the state from the state class
  @Select(ZooState) animals$: Observable<string[]>;

コンポネントからは@SelectデコレータによりStateからデータを呼び出すことができます。

AngularのNGXSについて簡単にまとめたみました。

多分間違っている箇所あると思うので、見かけた方はご指摘くだされると嬉しいです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0