在Angular应用程序中,ngrx(NgRx)是一个流行的状态管理库,它基于Redux模式。当涉及到异步操作时,如HTTP请求,我们通常需要等待这些操作完成后再更新状态。以下是如何使用ngrx来处理异步操作的基础概念和相关步骤:
// actions.ts
import { createAction, props } from '@ngrx/store';
export const loadData = createAction('[Data] Load Data');
export const loadDataSuccess = createAction('[Data] Load Data Success', props<{ data: any[] }>());
export const loadDataFailure = createAction('[Data] Load Data Failure', props<{ error: any }>());
// reducer.ts
import { createReducer, on } from '@ngrx/store';
import * as DataActions from './actions';
export interface State {
data: any[];
loading: boolean;
error: any;
}
export const initialState: State = {
data: [],
loading: false,
error: null,
};
const _dataReducer = createReducer(
initialState,
on(DataActions.loadData, (state) => ({ ...state, loading: true })),
on(DataActions.loadDataSuccess, (state, { data }) => ({ ...state, data, loading: false })),
on(DataActions.loadDataFailure, (state, { error }) => ({ ...state, error, loading: false }))
);
export function dataReducer(state, action) {
return _dataReducer(state, action);
}
// effects.ts
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import * as DataActions from './actions';
import { DataService } from '../services/data.service';
@Injectable()
export class DataEffects {
loadData$ = createEffect(() =>
this.actions$.pipe(
ofType(DataActions.loadData),
mergeMap(() =>
this.dataService.getData().pipe(
map((data) => DataActions.loadDataSuccess({ data })),
catchError((error) => of(DataActions.loadDataFailure({ error })))
)
)
)
);
constructor(private actions$: Actions, private dataService: DataService) {}
}
// component.ts
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import * as DataActions from './actions';
@Component({
selector: 'app-data',
templateUrl: './data.component.html',
styleUrls: ['./data.component.css']
})
export class DataComponent implements OnInit {
constructor(private store: Store) {}
ngOnInit() {
this.store.dispatch(DataActions.loadData());
}
}
问题:异步操作没有按预期触发状态更新。
原因:
解决方法:
通过以上步骤,你可以确保ngrx应用程序能够等待异步操作完成后再更新状态。
领取专属 10元无门槛券
手把手带您无忧上云