2017-04-01 3 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繰り返し、いくつかのコードを実行します。 1つの可能な実装

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 
    } 
} 
関連する問題