首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NGXS非活动超时

NGXS非活动超时
EN

Stack Overflow用户
提问于 2020-01-27 19:21:22
回答 2查看 511关注 0票数 1

在Angular项目中。我是NGXS的新手,正在尝试转换一个NGRX效果,它监视所有的动作,如果一个动作不是注销动作,它会重置一个计时器。如果计时器在另一个操作之前超时,它会自动执行用户注销。我不确定如何在NGXS中实现这一点。这是我的NGRX效果:

代码语言:javascript
复制
@Effect()
extendApplicationTimeout$: Observable<any> = this.actions$.pipe(
    switchMap((action: Action) => {
        if (action.type !== 'LogoutUser'){
            return timer(this.APPLICATION_TIMEOUT_TIME)
        }
    }),
    map(() => new LogoutUser())
);
EN

回答 2

Stack Overflow用户

发布于 2020-01-28 01:28:35

您可以使用Meta Reducer:https://www.ngxs.io/advanced/meta-reducer

代码语言:javascript
复制
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);
}

您可以像这样将其连接起来:

代码语言:javascript
复制
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)

如果您需要分派事件,则需要将useFactorydeps一起使用并注入Store,或者使用注入器来获取对Store的引用。

我还没有测试过,我不知道它是否会工作,希望它能把你推向正确的方向:

代码语言:javascript
复制
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 {}

实现

代码语言:javascript
复制
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);
  }
}
票数 0
EN

Stack Overflow用户

发布于 2020-01-28 09:05:32

另一种方法是监听NGXS动作流,以在顶层管理此计时器。

您可以创建一个可注入的服务,并通过APP_INITIALIZER令牌将其加载到app.module providers中。

代码语言:javascript
复制
@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())

  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59930122

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档