在 Ionic 2 / Angular 2 beta 10 中访问 window 对象

Accessing window object in Ionic 2 / Angular 2 beta 10

在 Angular 1.x 和 Ionic 1.x 中,我可以通过依赖注入访问 window 对象,如下所示:

angular.module('app.utils', [])

.factory('LocalStorage', ['$window', function($window) {
    return {
        set: function(key, value) {
          $window.localStorage[key] = value;
        },
        get: function(key, defaultValue) {
          return $window.localStorage[key] || defaultValue;
        }
    };
}]);

如何在 Angular 2 和 Ionic 2 中执行相同的操作?

您可以在不导入任何内容的情况下使用 window 对象,但只需在您的打字稿代码中使用它即可:

import { Component } from "@angular/core";

@Component({
     templateUrl:"home.html"
})
export class HomePage {

  public foo: string;

  constructor() {
    window.localStorage.setItem('foo', 'bar');

    this.foo = window.localStorage.getItem('foo');
  }
}

您还可以将 window 对象包装在一个服务中,这样您就可以模拟它进行测试。

一个天真的实现是:

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

@Injectable()
export class WindowService {
  public window = window;
}

然后您可以在引导应用程序时提供此信息,以便它随处可用。

import { WindowService } from './windowservice';

bootstrap(AppComponent, [WindowService]);

只需在您的组件中使用它即可。

import { Component } from "@angular/core";
import { WindowService } from "./windowservice";

@Component({
     templateUrl:"home.html"
})
export class HomePage {

  public foo: string;

  constructor(private windowService: WindowService) {
    windowService.window.localStorage.setItem('foo', 'bar');

    this.foo = windowService.window.localStorage.getItem('foo');
  }
}

更复杂的服务可以包装方法和调用,因此使用起来更愉快。