Angular应用程序的默认空闲超时时间是5分钟。可以通过在应用程序的根模块中配置Idle
服务来修改默认超时时间。
首先,安装@ng-idle/core
和@ng-idle/keepalive
依赖项:
npm install @ng-idle/core @ng-idle/keepalive
然后,在根模块中导入NgIdleModule
和KeepaliveModule
:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgIdleKeepaliveModule } from '@ng-idle/keepalive';
import { IdleModule } from '@ng-idle/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
NgIdleKeepaliveModule.forRoot(),
IdleModule.forRoot()
],
bootstrap: [AppComponent]
})
export class AppModule { }
接下来,在应用程序的根组件中使用Idle
服务来配置空闲超时时间:
import { Component } from '@angular/core';
import { Idle } from '@ng-idle/core';
@Component({
selector: 'app-root',
template: ` `
})
export class AppComponent {
constructor(private idle: Idle) {
// 设置空闲超时时间为5分钟
idle.setIdle(300);
// 设置警告时间为30秒
idle.setTimeout(30);
// 设置警告消息
idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);
// 启动Idle服务
idle.watch();
}
}
以上代码将将空闲超时时间设置为5分钟,警告时间设置为30秒,并启动Idle
服务。
注意:在应用程序中使用Idle
服务之前,需要确保用户已经登录,否则可以通过路由守卫或其他方式来限制访问。