Angular 17:保存更改后未定义 localStorage 错误且浏览器陷入重新加载状态

问题描述 投票:0回答:1

当我在 Angular 17 中运行项目时,它运行成功。但是,当我对代码进行一些更改并保存更改时:

The browser page stucks in a reloading state

还出现此错误:

Error during ngOnInit: ReferenceError: localStorage is not defined

这是我的 ngOnInit 代码块:

async ngOnInit() {
    try {
      await this.fetchUsers();
  
      this.chatService.fetchMessages();
      this.chatService.messages.subscribe((messages) => {
        this.messages = messages;
      });
  
      const users = this.authService.getUsers();
      const { username, id } = this.authService.getUserNameFromToken() || {};
      this.name = username ?? '';
      console.log("Display token name:", this.name);
      let token = localStorage.getItem('authToken');
      console.log("Token: ",token);
      this.id = id ?? '';
    } catch (error) {
      console.error("Error during ngOnInit:", error);
    }

  }

Here is image of browser page which stucks in loading state when i made changes in code and save them

angular typescript local-storage mean-stack
1个回答
0
投票

可能是浏览器缓存问题

有时,浏览器缓存或 cookie 可能会导致无限重新加载

或者您可以检查无限循环并调试日志

async ngOnInit() {
  try {
    console.log("Starting ngOnInit");

    await this.fetchUsers();
    console.log("Fetched users");

    this.chatService.fetchMessages();
    console.log("Fetched messages");

    this.chatService.messages.subscribe((messages) => {
      this.messages = messages;
      console.log("Received messages:", messages);
    });

    const users = this.authService.getUsers();
    const { username, id } = this.authService.getUserNameFromToken() || {};
    this.name = username ?? '';
    console.log("Display token name:", this.name);
    
    if (typeof window !== 'undefined' && window.localStorage) {
      let token = localStorage.getItem('authToken');
      console.log("Token: ", token);
    } else {
      console.log("localStorage is not available.");
    }

    this.id = id ?? '';
    console.log("ID:", this.id);

  } catch (error) {
    console.error("Error during ngOnInit:", error);
  }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.