作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
主页组件
ngOnInit()
{
console.log('loaded');
this.retrieveData();
}
retrieveData()
{
// this.dataService.getData().subscribe(...);
}
我正在加载组件时检索数据。当用户点击另一个 routerLink
,例如 SettingsComponent
并返回到 HomeComponent
时,当然会再次调用该函数,因为组件已再次加载。但是每次我返回组件时,它都会再次调用函数,这会产生太多不需要的 HTTP 请求。我需要防止这种情况并确保该函数仅在第一次被调用。我该怎么做呢?我应该使用其他组件生命周期钩子(Hook)吗?
最佳答案
好的,我看到您正在使用 service加载数据,这是一种好方法。
然后您可以简单地将数据缓存在某处,当您返回组件时检查该数据的缓存。我认为你可以将数据直接存储在你的服务中,这将把它保存在内存中,或者你可以把它放在 localStorage 中。
所以第一个选项看起来像:
data.service.ts
export class DataService {
private data: any[];
setData(data:any[]){
this.data = data;
}
getData(){
return this.data || [];
}
hasData(){
return this.data && this.data.length;
}
getData(){
// your implementation here
}
}
然后在 HomeComponent
里面retrieveData(){
if(this.dataService.hasData()){
// this will get the data which was previously stored in the memory
// and there will be no HTTP request
let data = this.dataService.getData();
// do something with data now ...
}else{
// old code
this.dataService.getData().subscribe(response => {
// but this time safe the data for future use
this.dataService.setData(response.data);
}, error => {
// handle errors
});
}
}
重要:如果使用这种方法,您应该在 app.module.ts -> providers
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [
DataService <---------- SEE HERE
],
bootstrap: [AppComponent]
})
export class AppModule { }
然后不这样做:
@Component({
selector: 'home',
templateUrl: '...',
styleUrls: ['...'],
providers: [
DataService <---- THEN DON'T put in component's providers
]
})
export class HomeComponent{ ... }
============================================ =
localStorage 方法
首页组件网
retrieveData()
{
let data = localStorage.getItem('yourDataName');
if (data === null){
// old code
this.dataService.getData().subscribe(response => {
// but this time safe the data for future use in localStorage
localStorage.setItem('yourDataName', response.data);
}, error => {
// handle errors
});
} else {
// seems that you already loaded this data
// do something with this data ...
}
}
这两种方法都有不能处理大量数据的局限性,当然如果你不想让使用你的应用的用户的浏览器崩溃的话:)
关于angular - 如何在 ngOnInit() 上只运行一次函数,而不是在从另一个 routerLink 返回时再次运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44406583/
我是一名优秀的程序员,十分优秀!