访问Ionic 2/Angular 2 beta 10中的窗口对象

Aki*_*asu 5 javascript typescript ionic2 ionic3 angular

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

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;
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

我如何在Angular 2和Ionic 2中做同样的事情?

seb*_*ras 8

您可以在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');
  }
}
Run Code Online (Sandbox Code Playgroud)

您还可以将window对象包装在服务中,然后您可以将其模拟以用于测试目的.

一个天真的实现将是:

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

@Injectable()
export class WindowService {
  public window = window;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在引导应用程序时提供此功能,以便随处可用.

import { WindowService } from './windowservice';

bootstrap(AppComponent, [WindowService]);
Run Code Online (Sandbox Code Playgroud)

只需在组件中使用它.

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');
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  • @AkilanArasu只是第一次谷歌搜索https://github.com/marcmarc/angular2-localstorage (2认同)