localStorage is not defined (Angular Universal)

后端 未结 13 2498
情书的邮戳
情书的邮戳 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:17

    As wierd as this approach might seem, it is working, and I had to do none of the plumbing the other answers are suggesting.

    Step 1

    Install localstorage-polyfill: https://github.com/capaj/localstorage-polyfill

    Step 2

    Assuming you followed this step: https://github.com/angular/angular-cli/wiki/stories-universal-rendering, you should have a file called, server.js in your project root folder.

    In this server.js add this:

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

    Step 3

    Rebuild your project, npm run build:ssr, and all should work fine now.


    Does the above approach work? Yes, as far as I can tell.

    Is it the best? Maybe not

    Any performance issues? Not that I know of. Enlighten me.

    However, as it stands now, this is the dumbest, most cleanest approach to getting my localStorage to pass

提交回复
热议问题