从服务访问渲染器

时间:2017-03-15 18:49:21

标签: angularjs

我正在尝试让服务注册窗口上的点击事件回调。我宁愿不直接从我的代码访问全局窗口对象。我尝试使用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'));
  }
}

1 个答案:

答案 0 :(得分: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'));
  }
}