当我在 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);
}
}
可能是浏览器缓存问题
有时,浏览器缓存或 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);
}
}