在Angular项目中。我是NGXS的新手,正在尝试转换一个NGRX效果,它监视所有的动作,如果一个动作不是注销动作,它会重置一个计时器。如果计时器在另一个操作之前超时,它会自动执行用户注销。我不确定如何在NGXS中实现这一点。这是我的NGRX效果:
@Effect()
extendApplicationTimeout$: Observable<any> = this.actions$.pipe(
switchMap((action: Action) => {
if (action.type !== 'LogoutUser'){
return timer(this.APPLICATION_TIMEOUT_TIME)
}
}),
map(() => new LogoutUser())
);发布于 2020-01-28 01:28:35
您可以使用Meta Reducer:https://www.ngxs.io/advanced/meta-reducer
import { getActionTypeFromInstance } from '@ngxs/store';
export function extendApplicationPlugin(state, action, next) {
// Use the get action type helper to determine the type
if (getActionTypeFromInstance(action) !== LogoutUser.type) {
// do timer stuff...
}
// return the next function with the next state
return next(state, action);
}您可以像这样将其连接起来:
import { NgModule } from '@angular/core';
import { NGXS_PLUGINS } from '@ngxs/store';
@NgModule({
imports: [NgxsModule.forRoot([])],
providers: [
{
provide: NGXS_PLUGINS,
useValue: extendApplicationPlugin,
multi: true
}
]
})
export class AppModule {}你就不用这样做了。你也可以在你自己的插件中使用getActionTypeFromInstance(action)。
如果您需要分派事件,则需要将useFactory与deps一起使用并注入Store,或者使用注入器来获取对Store的引用。
我还没有测试过,我不知道它是否会工作,希望它能把你推向正确的方向:
import { NgModule } from '@angular/core';
import { NGXS_PLUGINS, Store } from '@ngxs/store';
@NgModule({
imports: [NgxsModule.forRoot([])],
providers: [
{
provide: NGXS_PLUGINS,
useFactory: extendApplicationPlugin,
deps: [Store],
multi: true,
}
]
})
export class AppModule {}实现
import { getActionTypeFromInstance, Store } from '@ngxs/store';
export function extendApplicationPlugin(store: Store) {
return function extendApplicationPlugin(state, action, next) {
// Use the get action type helper to determine the type
if (getActionTypeFromInstance(action) !== LogoutUser.type) {
// do timer stuff...
// store.dispatch()
}
// return the next function with the next state
return next(state, action);
}
}发布于 2020-01-28 09:05:32
另一种方法是监听NGXS动作流,以在顶层管理此计时器。
您可以创建一个可注入的服务,并通过APP_INITIALIZER令牌将其加载到app.module providers中。
@Injectable({provideIn: 'root'})
export class AppTimeoutHandler {
constructor(private actions$: Actions, private store: Store) {
...// subscribe to `actions$` and then reset timer
...// when timer expires, store.dispatch(.. new LogoutAction())
}
}https://stackoverflow.com/questions/59930122
复制相似问题