【发布时间】:2018-11-03 00:30:03
【问题描述】:
我编写了一个可以跟踪时间的组件。我目前正在使用Localstorage 来保存currentTime,以防万一用户点击刷新。但是,我发现这个解决方案并不是一个很好的解决方案,因为用户可以编辑localstorage。另一方面,我可以使用数据库来存储这些信息,但它会减慢我不想要的页面速度。
除了使用LocalStorage 来存储我的时间之外,还有其他解决方案吗?我不希望用户编辑localstorage。
export class MainComponent implements OnInit {
private start: number = null;
private uiTimerId: number = null;
constructor() {
}
private updateUI(): void {
let delta = performance.now() - this.start;
this.someUIElement.textContent = delta.toFixed() + "ms";
}
ngOnInit() {
this.start = parseFloat( window.localStorage.getItem( "timerStart" ) );
if( !this.start ) {
this.start = performance.now();
window.localStorage.setItem( "timerStart", this.start );
}
this.uiTimerId = window.setInterval( this.updateUI.bind(this), 100 ); // 100ms UI updates, not 1000ms to reduce UI jitter
}
buttonClick = function() {
if( this.uiTimerId != null ) {
window.clearInterval( this.uiTimerId );
window.localStorage.removeItem( "timerStart" );
}
}
}
【问题讨论】:
-
询问除了使用数据库存储之外是否还有其他解决方案。出于效率目的。
-
从数据库的可能性来看,我假设您必须登录才能使用此服务。 currentTime是否需要在不同的登录之间保留,还是可以在注销后丢弃?
-
@Emenpy 要么将其保存在服务中,要么学习如何使用像 store github.com/ngrx/store 这样的 redux ...我不明白为什么一个简单的服务不会这样做:p
-
@FRECIA 即使它在服务中,刷新也会重新启动计时器。
-
@NocNit 我正在使用计时器来测量用户在某个页面停留的时间。注销/重新登录后,计时器将重置。但是,我不希望它在用户刷新页面时重置。通过存储在 localStorage 中,如果它被重置,我可以从 localstorage 中检索时间。
标签: javascript angular typescript