要使用Angular NgRx调度动作方法,首先需要设置好NgRx Store和Actions。
npm install @ngrx/store @ngrx/effects @ngrx/store-devtools
import { createAction, props } from '@ngrx/store';
export const increment = createAction('[Counter] Increment');
export const decrement = createAction('[Counter] Decrement');
export const reset = createAction('[Counter] Reset');
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
export const initialState = 0;
export const counterReducer = createReducer(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(reset, () => initialState)
);
import { StoreModule } from '@ngrx/store';
import { counterReducer } from './counter.reducer';
@NgModule({
imports: [
StoreModule.forRoot({ count: counterReducer })
],
})
export class AppModule { }
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
@Component({
selector: 'app-counter',
template: `
{{ count$ | async }}
`,
})
export class CounterComponent {
count$ = this.store.select('count');
constructor(private store: Store<{ count: number }>) {}
increment() {
this.store.dispatch(increment());
}
decrement() {
this.store.dispatch(decrement());
}
reset() {
this.store.dispatch(reset());
}
}
注意:上述代码中的count
是Reducer中定义的状态属性名,需要根据实际情况进行修改。
这样就可以在Angular应用中使用NgRx调度动作方法了。