好的,我看到您正在使用服务来加载数据,这是一个好方法。
然后,您可以简单地将数据缓存在某个地方,当您返回组件时,请检查缓存中的数据。我认为您可以将数据直接存储在您的服务中,这会将其保存在内存中,或者您可以将其放入localStorage
所以第一个选项看起来像:
数据服务.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 ...
}
}
这两种方法都有一个局限性,即您不能处理大量数据,当然,如果您不想破坏正在使用您的应用程序的用户的浏览器:)