Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage is not defined (Angular Universal)

I am using universal-starter as backbone.

When my client starts, it read a token about user info from localStorage.

@Injectable() export class UserService {   foo() {}    bar() {}    loadCurrentUser() {     const token = localStorage.getItem('token');      // do other things   }; } 

Everything works well, however I got this in the server side (terminal) because of server rendering:

EXCEPTION: ReferenceError: localStorage is not defined

I got the idea from ng-conf-2016-universal-patterns that using Dependency Injection to solve this. But that demo is really old.

Say I have these two files now:

main.broswer.ts

export function ngApp() {   return bootstrap(App, [     // ...      UserService   ]); } 

main.node.ts

export function ngApp(req, res) {   const config: ExpressEngineConfig = {     // ...     providers: [       // ...       UserService     ]   };    res.render('index', config); } 

Right now they use both same UserService. Can someone give some codes to explain how to use different Dependency Injection to solve this?

If there is another better way rather than Dependency Injection, that will be cool too.


UPDATE 1 I am using Angular 2 RC4, I tried @Martin's way. But even I import it, it still gives me error in the terminal below:

Terminal (npm start)

/my-project/node_modules/@angular/core/src/di/reflective_provider.js:240 throw new reflective_exceptions_1.NoAnnotationError(typeOrFunc, params); ^ Error: Cannot resolve all parameters for 'UserService'(Http, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'UserService' is decorated with Injectable.

Terminal (npm run watch)

error TS2304: Cannot find name 'LocalStorage'.

I guess it is somehow duplicated with the LocalStorage from angular2-universal (although I am not using import { LocalStorage } from 'angular2-universal';), but even I tried to change mine to LocalStorage2, still not work.

And in the meanwhile, my IDE WebStorm also shows red:

enter image description here

BTW, I found a import { LocalStorage } from 'angular2-universal';, but not sure how to use that.


UPDATE 2, I changed to (not sure whether there is a better way):

import { Injectable, Inject } from '@angular/core'; import { Http } from '@angular/http'; import { LocalStorage } from '../../local-storage';  @Injectable() export class UserService {   constructor (     private _http: Http,     @Inject(LocalStorage) private localStorage) {}  // <- this line is new    loadCurrentUser() {     const token = this.localStorage.getItem('token'); // here I change from `localStorage` to `this.localStorage`      // …   }; } 

This solves the issue in UPADAT 1, but now I got error in the terminal:

EXCEPTION: TypeError: this.localStorage.getItem is not a function

like image 846
Hongbo Miao Avatar asked Aug 22 '16 17:08

Hongbo Miao


People also ask

Is not defined Angular universal?

This error can be caused by a reference to the Window object if you are rendering your application from a server like Node. js. I will share how I have solved this issue, in my case this was caused by HammerJS which does not support server-rendered applications.

How do I use LocalStorage in Angular 11?

To use it, first install it in your Angular project using npm . Once you have it installed, you can import the library in the LocalService . Now, you can use the above two methods to encrypt and decrypt before storing and fetching data from local storage. Save the Angular app and run the application.

What is LocalStorage in Angular?

The purpose of LocalStorage is saving information on the client side and then we could use this information somewhere in project. LocalStorage in Angular. Every project is develops and evolves that mean maybe someday we will need to add a new property for example surname.


2 Answers

These steps resolved my issue:

Step 1: Run this command:

npm i localstorage-polyfill --save 

Step 2: Add these two lines in server.ts file:

import 'localstorage-polyfill'  global['localStorage'] = localStorage; 

Once you are done, run build command (eg: npm run build:serverless)

All set now. Start the server again and you can see the issue is resolved.

Note: Use localStorage not window.localStorage, eg: localStorage.setItem(keyname, value)

like image 150
Abhijeet Verma Avatar answered Sep 22 '22 14:09

Abhijeet Verma


Update for newer versions of Angular

OpaqueToken was superseded by InjectionToken which works much in the same way -- except it has a generic interface InjectionToken<T> which makes for better type checking and inference.

Orginal Answer

Two things:

  1. You are not injecting any object that contains the localStorage object, you are trying to access it directly as a global. Any global access should be the first clue that something is wrong.
  2. There is no window.localStorage in nodejs.

What you need to do is inject an adapter for localStorage that will work for both the browser and NodeJS. This will also give you testable code.

in local-storage.ts:

import { OpaqueToken } from '@angular/core';  export const LocalStorage = new OpaqueToken('localStorage'); 

In your main.browser.ts we will inject the actual localStorage object from your browser:

import {LocalStorage} from './local-storage.ts';  export function ngApp() {   return bootstrap(App, [     // ...      UserService,     { provide: LocalStorage, useValue: window.localStorage}   ]); 

And then in main.node.ts we will use an empty object:

...  providers: [     // ...     UserService,     {provide: LocalStorage, useValue: {getItem() {} }} ] ... 

Then your service injects this:

import { LocalStorage } from '../local-storage';  export class UserService {      constructor(@Inject(LocalStorage) private localStorage: LocalStorage) {}      loadCurrentUser() {          const token = this.localStorage.getItem('token');         ...     }; } 
like image 39
Martin Avatar answered Sep 19 '22 14:09

Martin