localStorage is not defined (Angular Universal)

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

    You can use PLATFORM_ID token to check whether the current platform is browser or server.

    import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
    import { isPlatformBrowser } from '@angular/common';
    
    @Component({
      selector: "app-root",
      templateUrl: "./app.component.html"
    })
    export class AppComponent implements OnInit {
    
       constructor(@Inject(PLATFORM_ID) private platformId: Object) {  }
    
       ngOnInit() {
    
         // Client only code.
         if (isPlatformBrowser(this.platformId)) {
            let item = {key1: 'value1', key2: 'valu2' };
            localStorage.setItem( itemIndex, JSON.stringify(item) );
         }
    
       }
     }
    

提交回复
热议问题