NGRXを使用して角度での基本的な状態管理
8530 ワード
NGRXとは❤️
NGRXはあなたの角度のアプリケーションのための反応状態管理を提供するオープンソースライブラリです.RedUxに触発さ、NGRXは、真実の単一のソースとして角度アプリケーションでデータを維持する方法を提供します.NGRXデータストリームと対話するストリームを使用します.
NGRXの使い方
NGRXを構成する5つの部分があります.
鍵概念
純粋な関数:内部状態を持たない関数としての純粋な関数.これは、実行するすべての操作がその状態に影響されず、同じ入力パラメーターを与えられ、同じ決定性出力を生成することを意味します.
ストア:お客様のアプリケーションの状態は、ストア内で維持されます.その店は不変だ.
還元器:現在の状態と引数としてのアクションを取る関数であり、新しい状態結果を格納するために返します.言い換えると、(状態、アクション)=> newstate
アクション:アクションは、コンポーネントまたはサービスから送信できるユニークなイベントです.
セレクタ:純粋な関数を選択し、派生し、構成の作品を構成するために使用されます.
効果:アクションの結果として発生し、呼び出されたときにアクションを作成することもできます.主な責任は、Asyncの副作用(Apisへのサービス呼び出しのような)を作成することです.
NGRXを使用して状態管理に深いダイビングにサンプルアプリケーションを起動しましょう
👉 新しい角度アプリケーションを作成します
ng new redux-angular-app
👉 インストール/npmモジュールを保存します.
npm i @ngrx/store --save
👉 アプリのupdations.モジュール// Ngrx imports for store and newly created reducer
import { StoreModule } from '@ngrx/store';
import { simpleReducer } from './ngrx/simple.reducer';
...
imports: [
...
StoreModule.forRoot({ message: simpleReducer })
],
👉 SimpleReducerを作成するimport { Action } from "@ngrx/store";
export function simpleReducer(state: string = 'Hello World', action: Action) {
console.log(action.type, state);
// updating and returning the newly state to store on the basis of dispatched action type
switch (action.type) {
case 'SPANISH':
return state = 'Hola Mundo';
case 'FRENCH':
return state = 'Bonjour le monde';
default:
return state;
}
}
👉 望ましいコンポーネントの中のNGRX/Reduxアクション// import the store from ngrx and observable from rxjs
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
...
interface AppState {
message: string;
}
...
// an observable in which we get updated state from store
message$: Observable<string>
constructor(
private store: Store<AppState>,
) {
// retrieve data from ngrx store
this.message$ = this.store.select('message');
}
ngOnInit(): void {
}
// dispatching actions to reducer for further task to update the store with newly state
spanishMessage() {
this.store.dispatch({ type: 'SPANISH' });
}
frenchMessage() {
this.store.dispatch({ type: 'FRENCH' });
}
<p>{{message$ | async}}</p>
<button (click)="spanishMessage()">Spanish</button>
<button (click)="frenchMessage()">French</button>
ギタブ:https://github.com/muhammadawaisshaikh/redux-angular-ngrx/ハッピーredux🚀
Reference
この問題について(NGRXを使用して角度での基本的な状態管理), 我々は、より多くの情報をここで見つけました https://dev.to/muhammadawaisshaikh/state-management-in-angular-using-ngrx-inspired-by-redux-11l5テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol