[英]Angular - Code to trigger only first time Load
I've created a skeleton structure for my app in Angular 9. The skeleton code initializes in ngAfterViewInit()
hook.我在 Angular 9 中为我的应用程序创建了一个骨架结构。骨架代码在ngAfterViewInit()
挂钩中初始化。
ngAfterViewInit() {
this.showSpinner = false;
this.interval = setInterval(() => {
this.domLoaded = true;
}, 5000);
}
I have also used ngAfterContentInit()
but that didn't work我也使用ngAfterContentInit()
但这没有用
There are a lot of ways to go about with this (also, I do agree with the comment by Pardeep - you should look for other ways) but sticking to your question, try to save the state within localStorage/sessionStorage so that the information is not lost after navigating to other pages in your site. go 有很多方法可以解决这个问题(另外,我同意 Pardeep 的评论 - 你应该寻找其他方法)但坚持你的问题,尝试将 state 保存在 localStorage/sessionStorage 中,以便信息是导航到您网站中的其他页面后不会丢失。 So something like this will work:所以这样的事情会起作用:
ngAfterViewInit() {
this.showSpinner = false;
if (!sessionStorage.getItem('siteInit')) {
this.interval = setInterval(() => {
this.domLoaded = true;
sessionStorage.setItem('siteInit', 'true');
}, 5000);
} else {
this.domLoaded = true;
}
}
The ngAfterViewInit()
lifecycle hook gets called every time, your component is loaded.每次加载组件时都会调用ngAfterViewInit()
生命周期挂钩。 To achieve your required functionality you could use a Singleton Service and set the domLoaded
property there.为了实现您所需的功能,您可以使用Singleton 服务并在那里设置domLoaded
属性。
Assuming you placed <router-outlet></router-outlet>
in app.component.ts
, this component will only load once and the subsequent navigation will happen within the application (Single Page Application benefits).假设您将<router-outlet></router-outlet>
放在app.component.ts
中,该组件只会加载一次,随后的导航将在应用程序内进行(单页应用程序的好处)。
Therefore, you can run the code right there if this is what you need.因此,如果这是您需要的,您可以在此处运行代码。
If you want to only run the code once the first time a user accesses your page and not run it for subsequent refreshes , you can use the browser Local Storage to keep track of the state (mark if it's the first time accessing the page or not).如果您只想在用户第一次访问您的页面时运行代码而不运行它以进行后续刷新,您可以使用浏览器本地存储来跟踪 state(标记是否是第一次访问页面)。 Then you'd need to check on every page load whether you need to run the code or not.然后,您需要检查每个页面加载是否需要运行代码。
Strictly related to your question , if you're tracking the state of a spinner
, you most likely want it to run on every page refresh.与您的问题严格相关,如果您正在跟踪spinner
的 state,您很可能希望它在每次页面刷新时运行。 For this you can hold its state in a Service instead of Local Storage.为此,您可以将其 state 保存在服务而不是本地存储中。
Side note : Accessing browser's Local Storage is much more inefficient than accessing a variable that's already in memory.旁注:访问浏览器的本地存储比访问 memory 中已经存在的变量效率低得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.