在使用@ngrx/store时,State对象的当前值可以通过Store类的select方法获取。以下是获取State对象当前值的步骤:
@ngrx/store是Angular应用程序的状态管理库,基于Redux设计模式。它通过actions、reducers和selectors来管理应用程序的状态。
import { createReducer, on } from '@ngrx/store';
import { increment, decrement } from './counter.actions';
export const initialState = { count: 0 };
const _counterReducer = createReducer(
initialState,
on(increment, state => ({ count: state.count + 1 })),
on(decrement, state => ({ count: state.count - 1 }))
);
export function counterReducer(state, action) {
return _counterReducer(state, action);
}
import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { counterReducer } from './counter.reducer';
@NgModule({
imports: [
StoreModule.forRoot({ counter: counterReducer })
]
})
export class AppModule { }
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { selectCounterState } from './counter.selectors';
@Component({
selector: 'app-counter',
template: `
<div>Count: {{ count$ | async }}</div>
<button (click)="increment()">Increment</button>
<button (click)="decrement()">Decrement</button>
`
})
export class CounterComponent {
count$ = this.store.select(selectCounterState);
constructor(private store: Store) {}
increment() {
this.store.dispatch(increment());
}
decrement() {
this.store.dispatch(decrement());
}
}
import { createSelector } from '@ngrx/store';
import { AppState } from './app.state';
export const selectCounterState = (state: AppState) => state.counter;
这种状态管理方式适用于大型Angular应用程序,特别是当应用程序的状态变得复杂时。通过@ngrx/store,你可以将状态管理逻辑与组件逻辑分离,使代码更易于维护和测试。
通过以上步骤,你可以轻松地获取和使用@ngrx/store中的State对象的当前值。
领取专属 10元无门槛券
手把手带您无忧上云