Javascript 持续运行服务并检查变量的值

Javascript 持续运行服务并检查变量的值,javascript,angular,typescript,Javascript,Angular,Typescript,我创建了一些代码,可以告诉我用户窗口是否滚动超过某个点。我很快意识到这需要一种服务,因为其他组件也需要这种信息 我在逻辑中使用了@HostListener,并将得到结果。现在,这一切都在一个服务中,我只知道当我调用该服务时,窗口是否滚动超过某个点 问题是,我如何不断地呼叫服务?该服务有一个布尔值,我需要实时信息 服务 使用setInterval重复运行某些代码。一种可能的实现方式 import { Component, OnInit } from '@angular/core'; import

我创建了一些代码,可以告诉我用户窗口是否滚动超过某个点。我很快意识到这需要一种服务,因为其他组件也需要这种信息

我在逻辑中使用了@HostListener,并将得到结果。现在,这一切都在一个服务中,我只知道当我调用该服务时,窗口是否滚动超过某个点

问题是,我如何不断地呼叫服务?该服务有一个布尔值,我需要实时信息

服务
使用
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
  }
}
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()
  }
}
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
  }
}