[英]Is it possible to have Angular @HostListener('window:scroll',) in simple Service not Component or Directive
Is it possible to have Angular @HostListener('window:scroll',) in simple Service not Component or Directive code? 是否有可能在简单Service中没有组件@或指令代码中的Angular @HostListener('window:scroll',)?
I don't want to polute any of my components, since the awareness of scroll should be injected in several other services... Currently i have following code that compiles, but does not work somehow. 我不想污染我的任何组件,因为应该在其他几个服务中注入对滚动的了解……目前,我拥有以下可编译的代码,但无法正常工作。
import { Component, OnInit, Injectable, Inject, HostListener } from '@angular/core';
import { SearchService } from './search.service';
import { DOCUMENT } from '@angular/platform-browser';
const scrollStepToReload = 3700;
@Injectable()
export class ScrollWatcherService {
private maxReachedScroll = 0;
private lastLoadedAt = 0;
constructor(private searchService: SearchService, @Inject(DOCUMENT) private document: any) { }
@HostListener('window:scroll', ['$event'])
onScroll($event) {
const scrollOffset = window.pageYOffset || this.document.documentElement.scrollTop || this.document.body.scrollTop || 0;
console.debug("Scroll Event", scrollOffset);
if (scrollOffset > this.maxReachedScroll) {
this.maxReachedScroll = scrollOffset;
}
if (this.lastLoadedAt + scrollStepToReload < this.maxReachedScroll) {
this.lastLoadedAt = this.maxReachedScroll;
this.searchService.continueSearch();
}
}
}
Similar code works i Component as desired. 类似的代码可以根据需要在Component上运行。 Any ideas how to get it run in a service?
任何想法如何使其在服务中运行? or something similar?
或类似的东西?
You cannot have a HostListener in a service. 服务中不能包含HostListener。 Use the classic:
使用经典:
window.addEventListener('scroll', () => { console.log('scrolling'); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.