There's a nice q&a here on using localstorage and angular2. https://stackoverflow.com/a/39098748/6203604
This approach seems to work fine with an 'npm start'. However when you run 'npm run build' the error:
Property 'window' does not exist on type 'typeof ../browser.module' appears.
In 'Universal Gotchas' on https://github.com/angular/universal-starter it says
window, document, navigator, and other browser types - do not exist on the server - so using them, or any library that uses them (jQuery for example) will not work. You do have some options, if you truly need some of this functionality: If you need to use them, consider limiting them to only your main.client and wrapping them situationally with the imported isBrowser / isNode features from Universal. import { isBrowser, isNode } from 'angular2-universal'; Another option is using DOM from "@angular/platform-browser"
Would an isBrowser wrapper or using the platform browser be suitable here to refer to localStorage? Any examples of how best to write this?
e.g in browser.module.ts, is there something that should be done to wrap window.localStorage for the distributable bundle?
import {LocalStorage} from './local-storage.ts';
export function ngApp() {
return bootstrap(App, [
// ...
UserService,
{ provide: LocalStorage, useValue: window.localStorage}
]);
with something that's going to work with 'npm run build' distributable bundle?
Also, when running npm start, I get the error message: Unexpected token u.
This appears to be coming from the 'u' in useValue in the file, node.module.ts, as disapears and gets replaced with 'No provider for Token LocalStorage!'
...
providers: [
// ...
UserService,
{provide: LocalStorage, useValue: {getItem() {} }}
]
...
Anyone getting something similar. Ideas?
You can use "fake" storage service for the server that dont actualy access
window
, and use DI to set it at the server module, and the rightwindow
access-able for the browser module. A good example can be found here