localStorage is not defined (Angular Universal)

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

    This is how we have it in our project, as per from this github comment:

    import { OnInit, PLATFORM_ID, Inject } from '@angular/core';
    import { isPlatformServer, isPlatformBrowser } from '@angular/common';
    
    export class SomeClass implements OnInit {
    
        constructor(@Inject(PLATFORM_ID) private platformId: Object) { }
    
        ngOnInit() {
            if (isPlatformServer(this.platformId)) {
                // do server side stuff
            }
    
            if (isPlatformBrowser(this.platformId)) {
               localStorage.setItem('myCats', 'Lissie & Lucky')
            }
        }    
    }
    

提交回复
热议问题