2017-03-15 63 views
0

我想讓一個服務爲窗口上的點擊事件註冊一個回調。我寧願不直接從我的代碼訪問全局窗口對象。我嘗試使用Renderer並註冊一個全局偵聽器,但在瀏覽器中失敗,說明Renderer沒有提供程序。我在組件中使用它,但我似乎無法在服務中使用它。什麼是完成這個的首選方法?從服務訪問呈現器

這裏是我當前的工作方式:

import { Injectable } from '@angular/core'; 
import { Observable } from 'rxjs/Observable'; 

@Injectable() 
export class MyService { 
    constructor() { 
    Observable.fromEvent(window, 'click').subscribe(() => console.log('window click received')); 
    } 
} 

這裏是我想要做什麼,但它失敗:

import { Injectable, Renderer } from '@angular/core'; 
import { Observable } from 'rxjs/Observable'; 
import { Observer } from 'rxjs/Observer'; 

@Injectable() 
export class MyService { 
    constructor (private renderer: Renderer) { 
    let clickEvent = new Observable<Event>(
     (observer: Observer<Event>) => { 
     this.renderer.listenGlobal('window', 'click', (evt: Event) => 
      { 
      observer.next(evt); 
      }) 
     }); 
    clickEvent.subscribe(() => console.log('window click received')); 
    } 
} 

回答

0

您可以通過RendererFactory2到服務並創建新實例Renderer2:

import { Injectable, RendererFactory2, Renderer2 } from '@angular/core'; 
import { Observable } from 'rxjs/Observable'; 
import { Observer } from 'rxjs/Observer'; 

@Injectable() 
export class MyService { 
    private renderer: Renderer2; 

    constructor (rendererFactory: RendererFactory2) { 
    this.renderer = rendererFactory.createRenderer(null, null); 
    let clickEvent = new Observable<Event>(
     (observer: Observer<Event>) => { 
     this.renderer.listenGlobal('window', 'click', (evt: Event) => 
      { 
      observer.next(evt); 
      }) 
     }); 
    clickEvent.subscribe(() => console.log('window click received')); 
    } 
}