依赖注入 – Angular2 – 如何注入窗口到angular2服务

我在TypeScript中编写一个将使用localstorage的Angular2服务。并且我想将浏览器窗口对象的引用注入到我的服务中,因为我不想引用任何全局变量。喜欢角1.x $窗口。我怎么做?
这对我目前工作(2017-01,角度2.1.2与AoT,测试角度cli和自定义webpack构建):

首先,创建一个注入服务,提供对窗口的引用:

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

function getwindow (): any {
    return window;
}

@Injectable()
export class WindowRefService {
    get nativeWindow (): any {
        return getwindow();
    }
}

现在,使用您的根AppModule注册该服务,以便它可以注入无处不在:

import { WindowRefService } from './window-ref.service';

@NgModule({        
  providers: [
    WindowRefService 
  ],...
})
export class AppModule {}

然后稍后在你需要注入窗口:

import { Component} from '@angular/core';
import { WindowRefService } from './window-ref.service';

@Component({ ... })
export default class MyCoolComponent {
    private _window: Window;

    constructor (
        windowRef: WindowRefService
    ) {
        this._window = windowRef.nativeWindow;
    }

    public doThing (): void {
        let foo = this._window.XMLHttpRequest;
    }
...

编辑:更新与Truchainz建议。编辑2:更新为角度2.1.2编辑3:添加了AoT注释编辑4:添加任何类型的解决办法说明edit5:更新的解决方案使用WindowRefService修复了一个错误,我得到时使用以前的解决方案与不同的构建

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...