2017-04-01 32 views
0

我創建了一些代碼,告訴我用戶窗口是否滾動到某個點之外。我很快意識到這需要成爲一項服務,因爲其他組件也需要這些信息。不斷運行服務並檢查變量的值

我在邏輯中使用了@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

使用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 
    } 
}