私はangular + ngrxを初めて使用し、大規模な適切な制御フローについて質問があります。Cars
車のリストをロードして新しい車を作成できるコンポーネントがあるとします。これらのエフェクトが実行されるSUCCESS
と、ディスパッチしてFAILURE
アクションを実行します。私のngOnInit
場合、適切に実行するために、これらの成功/失敗アクションのそれぞれにサブスクライブしています-次のようなものです。
ngOnInit() {
this.actions$
.pipe(
ofType<fromCarsActions.GetCarsSuccessAction>(fromCarsActions.CarsActionTypes.GET_CARS_SUCCESS),
takeUntil(this.unsubscribe$)
)
.subscribe(results => {
// do something if load all cars SUCCEEDS
});
this.actions$
.pipe(
ofType<fromCarsActions.GetCarsFailureAction>(fromCarsActions.CarsActionTypes.GET_CARS_FAILURE),
takeUntil(this.unsubscribe$)
)
.subscribe(results => {
// do something if load all cars FAILS
});
this.actions$
.pipe(
ofType<fromCarsActions.AddCarSuccessAction>(fromCarsActions.CarsActionTypes.ADD_CAR_SUCCESS),
takeUntil(this.unsubscribe$)
)
.subscribe(results => {
// do something if add car SUCCEEDS
});
this.actions$
.pipe(
ofType<fromCarsActions.AddCarsFailureAction>(fromCarsActions.CarsActionTypes.ADD_CAR_FAILURE),
takeUntil(this.unsubscribe$)
)
.subscribe(results => {
// do something if add car FAILS
});
}
これらすべてのSUCCESS / FAILUREアクションをサブスクライブすることは、数が少ない場合は問題ありませんが、より複雑なコンポーネントの場合はすぐに手に負えなくなる可能性があります。
私ができる別のオプションは、エフェクト自体に適切なアクションをディスパッチすることですが、それではエフェクトを再利用可能にすることはできません。
だから私の質問は、NGRXを使用してバックエンドと通信し、複数の異なる効果の成功/失敗のサブスクライブ/リスニングを簡単に管理するコンポーネントのベストプラクティスは何ですか?
これは少し抽象的な質問だと思いますので、何か明確にできるかどうか教えてください。
アクションをトリガーします
アクションは、レデューサー(ストアのみを更新します)またはエフェクト(DBからデータをフェッチするサービスを処理します)をトリガーします
次に、セレクターにサブスクライブして変更を取得できます。
あなたの場合、アクションを作成します-
export const loadCars = createAction('Load Car data');
export const getcarsSuccess = createAction('Get Car data Success', props<{ carData: any }>());
export const getCarsError = createAction('Get Car data Error', props<{ errorResponse: any}>());
export const createCars = createAction('Add Car data');
export const createCarsSuccess = createAction('Add Car data Success', props<{ carData: any }>());
export const createCarsError = createAction('Add Car data Error', props<{ errorResponse: any}>());
上記のアクションは、エフェクトまたはレデューサーをトリガーできます
有効:
@Effect()
public loadCarData$ = createEffect(() => this.actions$.pipe(
ofType(actions.loadCars ) ...
レデューサーの場合:
const initReducer = createReducer(
initialIState,
on(actiona.loadCarData, state => (state)))
セレクター内:
export const carDataLoaded = (state: fromReducer.carData) => state.carData ;
export const getCarData = createSelector(
getInitState,
carDataLoaded
);
最後に、コンポーネント内:
セレクターgetCarDataをサブスクライブできるため、コンポーネント-アクション-エフェクト-レデューサー-セレクター-コンポーネント
コンプで
private carStore: Store<carStore>
this.carStore.dispatch(new loadCars ()); //dispatch load Cars Action
this.carStore.pipe(select(
getCarData })
).subscribe(cars => console.log(cars)) // subscribe to selector
注:前述のように、コンポーネントから直接任意のアクションをサブスクライブできますが、NGRX状態管理を使用する目的には役立ちません。
AngularアプリのどこからでもNGRXストアを更新し、アプリのどこからでもストアデータにアクセスできます。データの状態を維持することを心配することなく。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加