Accessing window object in Ionic 2 / Angular 2 beta 10

13,095

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.

Share:
13,095
Akilan Arasu
Author by

Akilan Arasu

Chennai based iOS Developer.

Updated on June 12, 2022

Comments

  • Akilan Arasu
    Akilan Arasu almost 2 years

    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?

  • sebaferreras
    sebaferreras over 7 years
    Thanks for the edit @toskv. I'd add a constructor in the WindowService code with a nullable parameter, so in the tests you could send a mock object with the methods you want to test.
  • Akilan Arasu
    Akilan Arasu over 7 years
    Thank you very much toskv and @sebaferreras. I understand it better now. Is it also possible to write custom setters/getters for localStorage?
  • toskv
    toskv over 7 years
    @AkilanArasu everything is possible! :) there's nothing stopping you from adding other methods/getters/setters to that service.
  • toskv
    toskv over 7 years
    @AkilanArasu as a matter of design though, I'd make a separate service for local storage. I also bet someone already made one. ;)
  • toskv
    toskv over 7 years
    @AkilanArasu just the first google search github.com/marcj/angular2-localstorage
  • Akilan Arasu
    Akilan Arasu over 7 years