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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With