localStorage is not defined (Angular Universal)

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

    I don't think this is a good solution, but I was stucked with the same problem using aspnetcore-spa generator and solved it this way:

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

    This condition prevents client code from running on the server-side where 'window' object doesn't exist.

提交回复
热议问题