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:You could also wrap the
window
object inside a service so then you can mock it for testing purposes.A naive implementation would be:
You can then provide this when bootstrapping the application so it's available everywhere.
And just use it in your components.
A more sophisticated service could wrap the methods and calls so it's more pleasant to use.