在具有@ngrx/effects@4.1.1和@ngrx/store@4.1.1的Angular 4中,要从观察值中获取计数,可以按照以下步骤进行操作:
npm install @ngrx/effects@4.1.1 @ngrx/store@4.1.1
// counter.state.ts
export interface CounterState {
count: number;
}
export const initialState: CounterState = {
count: 0
};
// counter.actions.ts
import { createAction } from '@ngrx/store';
export const increment = createAction('Counter Increment');
// counter.reducer.ts
import { createReducer, on } from '@ngrx/store';
import { increment } from './counter.actions';
import { initialState } from './counter.state';
export const counterReducer = createReducer(
initialState,
on(increment, (state) => {
return {
...state,
count: state.count + 1
};
})
);
// app.module.ts
import { StoreModule } from '@ngrx/store';
import { counterReducer } from './counter.reducer';
@NgModule({
imports: [
StoreModule.forRoot({ counter: counterReducer })
]
})
export class AppModule { }
// counter.selectors.ts
import { createSelector, createFeatureSelector } from '@ngrx/store';
import { CounterState } from './counter.state';
export const selectCounterState = createFeatureSelector<CounterState>('counter');
export const selectCount = createSelector(
selectCounterState,
(state: CounterState) => state.count
);
// counter.effects.ts
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { tap } from 'rxjs/operators';
import { selectCount } from './counter.selectors';
@Injectable()
export class CounterEffects {
logCount$ = createEffect(() => {
return this.actions$.pipe(
ofType('[Counter] Increment'),
select(selectCount),
tap((count) => {
console.log('Count:', count);
})
);
});
constructor(private actions$: Actions) {}
}
// app.module.ts
import { EffectsModule } from '@ngrx/effects';
import { CounterEffects } from './counter.effects';
@NgModule({
imports: [
EffectsModule.forRoot([CounterEffects])
]
})
export class AppModule { }
通过以上步骤,你可以在具有@ngrx/effects@4.1.1和@ngrx/store@4.1.1的Angular 4应用程序中从观察值中获取计数值。这样做的好处是可以将状态和副作用(例如日志记录)与应用程序的其他部分分离开来,使代码更加模块化和可维护。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云