gpt4 book ai didi

javascript - 如何使用window.location防止不断刷新 Angular 页面

转载 作者:行者123 更新时间:2023-12-02 20:51:50 24 4
gpt4 key购买 nike

我有一个简单的 Angular 页面,由于我的项目中的一些要求,我需要在加载时手动刷新它。我添加了一个代码,它工作正常,但不断刷新页面。我需要阻止这里继续刷新。下面是代码。

home.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
template: '<button (click)="gonextPage()">Go to next page</button>',
styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
window.location.reload();
/* First data */
console.log('hello');
}

}

最佳答案

不知道为什么要刷新页面。

但是你的情况发生的是

第一次 app-home 初始化并刷新页面。页面重新加载后,app-home 再次初始化并刷新页面,依此类推。

所以为了防止你有一个 hacky 解决方案。在某些情况下这显然会失败。

解决办法是

ngOnInit() {
if (!sessionStorage.getItem('isPageRefreshed')) {
sessionStorage.setItem('isPageRefreshed', 'true');
// This will reload page once prevent reloading of page again for that session.
window.location.reload();

}
}

关于javascript - 如何使用window.location防止不断刷新 Angular 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61587593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com