我创建了一些代码,告诉我用户窗口是否滚动超过某一点。我很快意识到这需要成为一项服务,因为其他组件也需要这些信息。
我在逻辑中使用了@HostListener并获得了结果。现在这一切都在服务中,我只知道当我调用服务时窗口是否滚动超过某一点。
问题是,我该如何不断拨打该服务?该服务中有一个布尔值,我需要实时信息。
import { Injectable, OnInit, HostListener, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Injectable()
export class WindowScrollService {
public navIsFixed: boolean = false;
constructor(@Inject(DOCUMENT) private document: Document) {
}
@HostListener("window:scroll", [])
onWindowScroll() {
let number = this.document.body.scrollTop;
if (number > 20) {
this.navIsFixed = true;
console.log(this.navIsFixed);
} else if (this.navIsFixed && number < 10) {
this.navIsFixed = false;
console.log(this.navIsFixed);
}
}
}
import { Component, OnInit } from '@angular/core';
import { WindowScrollService } from '../window-scroll.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
public navIsFixed: boolean;
constructor( private windowscrollservice : WindowScrollService) {
this.navIsFixed = this.windowscrollservice.navIsFixed;
}
ngOnInit(){
this.windowscrollservice.onWindowScroll()
}
}
答案 0 :(得分:0)
使用setInterval
重复运行一些代码。一种可能的实现
import { Component, OnInit } from '@angular/core';
import { WindowScrollService } from '../window-scroll.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
public navIsFixed: boolean;
public interval;
constructor( private windowscrollservice : WindowScrollService) {
this.navIsFixed = this.windowscrollservice.navIsFixed;
}
ngOnInit(){
// run every 500ms
this.interval = setInterval(() => this.windowscrollservice.onWindowScroll(), 500);
// use clearInterval(this.interval) to stop
}
}