angular - 让@HostListener 在开始之前等待
问题描述
我正在将@HostListener 滚动事件用于角度,我希望能找到一种方法让它在它执行任何操作之前等待 3 秒,但仅在第一次触发时
@HostListener('window:scroll', ['$event']) getScrollHeight(event) {
const numberWhenItEntersViewport =
document.getElementById("innerScreenSection").offsetTop -
document.documentElement.clientHeight;
const yValueBottomOfElement =
document.getElementById("innerScreenSection").offsetTop +
document.getElementById("innerScreenSection").offsetHeight;
const elementHeight = document.getElementById("innerScreenSection")
.offsetHeight;
// if the element is where I want it and the timer has not gone yet then start the timer
// I realize I never declare waitedThreeSeconds, this is just for show of what I'm thinking
if (
waitedThreeSeconds === false &&
window.pageYOffset >= numberWhenItEntersViewport + 0.25 * elementHeight &&
window.pageYOffset <= yValueBottomOfElement - 0.3 * elementHeight
) {
// start timer and set waitedThreeSeconds to true? Idk how to do this without declaring
// a varible in here and having it turned back to false everytime this function is called
// it also does not seem to be able to read variables outside of this function
// specifically when they change it doesnt update
} else {
// 3 seconds have passed
console.log("scrolling and 3 seconds have passed");
}
}
解决方案
import { Subject, Observable } from 'rxjs';
import { delay, concatMap } from 'rxjs/operators';
// Delay amount (ms)
const DELAY = 3000;
...
// Setup
private readonly eventStream = new Subject<Event>();
// On the first emission, delay.
// After the delay, REMAP to the original stream (concatMap)
// USE first() to complete outer observable.
get eventStream$(): Observable<Event> {
return this.eventStream.pipe(
delay(DELAY),
first(),
concatMap(() => this.eventStream)
);
}
// Listen to clicks and emit
@HostListener('window:scroll', ['$event']) scroll(event: Event) {
this.eventStream.next(event);
}
constructor() {
this.eventStream$.subscribe(this.isScroll);
}
isScroll(event: Event) {
// Do math here.
console.log(event);
}
ngOnDestroy() {
// Cleanup.
this.eventStream.unsubscribe();
}
现在我们可以继续限制响应等。
推荐阅读
- seaborn - 为 seaborn 热图分配特定颜色
- node.js - React 在极端套接字更新上执行缓慢
- java - 传感器数据存储以前的值,即使缓存被清除
- r - 寓言:从 ARIMA 模型中提取 p,d,q 规范
- python - Python split()列表索引超出范围与tweepy
- r - 为 R 中最昂贵和最便宜的观察结果着色
- sql-server - SQL Server - 错误:18456,严重性:14,状态:46 原因
- snowflake-cloud-data-platform - How to troubleshoot Snowpipe auto ingest failures?
- c - 我们如何在 DPDK 18.11.9 中访问已接收数据包的有效负载
- javascript - 自动填充 Google Place 无法在移动设备上运行