localStorage is not defined (Angular Universal)

后端 未结 13 2447
情书的邮戳
情书的邮戳 2020-11-29 01:26

I am using universal-starter as backbone.

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

@Injectable()
export class UserSe         


        
13条回答
  •  独厮守ぢ
    2020-11-29 02:06

    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)

提交回复
热议问题