Reputation: 8841
I have a function that I am using in my app, and one of the parameters for the function is an object:
const checkValues = {
promoId: ...,
...
unsaved: !JSON.parse(localStorage.getItem('unsaved')) ? [] : JSON.parse(localStorage.getItem('unsaved'))
}
However, the only error I am receiving when I serve up my project is this:
ReferenceError: localStorage is not defined at Object. (/home/meow/Development/dmc/cli_universal/dist/server.bundle.js:4145:23) at webpack_require (/home/meow/Development/dmc/cli_universal/dist/server.bundle.js:21:30) at Object. (/home/meow/Development/dmc/cli_universal/dist/server.bundle.js:4119:67) at webpack_require (/home/meow/Development/dmc/cli_universal/dist/server.bundle.js:21:30) at Object. (/home/meow/Development/dmc/cli_universal/dist/server.bundle.js:1728:69) at webpack_require (/home/meow/Development/dmc/cli_universal/dist/server.bundle.js:21:30) at Object. (/home/meow/Development/dmc/cli_universal/dist/server.bundle.js:1803:70) at webpack_require (/home/meow/Development/dmc/cli_universal/dist/server.bundle.js:21:30) at Object. (/home/meow/Development/dmc/cli_universal/dist/server.bundle.js:1509:79) at webpack_require (/home/meow/Development/dmc/cli_universal/dist/server.bundle.js:21:30)
How can I check if localStorage exists?
Upvotes: 1
Views: 5773
Reputation: 1303
localstorage is a browser component and you are trying to use that on server side, you will have to make sure that you are calling localstorage when you are on browser side only.
For that you can use angular isPlatformBrowser module.
example
import { isPlatformBrowser } from '@angular/common';
constructor(@Inject(PLATFORM_ID) private platformId: any) {}
ngOnInit() {
if (isPlatformBrowser(this.platformId)) {
this.id = localStorage.getItem('id');
}
}
Upvotes: 6
Reputation: 17
$scope.$watch Should resolve your issues, Ideally when you are trying to invoke a function which is outside of scop, you need to add $watch to get it rendered on to it.
Upvotes: -2
Reputation: 8324
If you check the documentation for the Universal Starter you'll the following section (as part of the Gotcha's):
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.
I suppose that's why you're getting this error.
Upvotes: 1