Accessing window object in Ionic 2 / Angular 2 bet

2019-02-14 12:16发布

In Angular 1.x and Ionic 1.x I could access the window object through dependency injection, like so:

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;
        }
    };
}]);

How can I do the same in Angular 2 & Ionic 2?

1条回答
成全新的幸福
2楼-- · 2019-02-14 13:21

You can use the window object without importing anything, but by just using it in your typescript code:

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');
  }
}

You could also wrap the window object inside a service so then you can mock it for testing purposes.

A naive implementation would be:

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

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

You can then provide this when bootstrapping the application so it's available everywhere.

import { WindowService } from './windowservice';

bootstrap(AppComponent, [WindowService]);

And just use it in your components.

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');
  }
}

A more sophisticated service could wrap the methods and calls so it's more pleasant to use.

查看更多
登录 后发表回答