我如何只在ngOnInit()上运行一个函数,而不是在从另一个routerLink返回时再次运行? [英] How do I run a function on ngOnInit() only once and not again upon returning back from another routerLink?

查看:77
本文介绍了我如何只在ngOnInit()上运行一个函数,而不是在从另一个routerLink返回时再次运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HomeComponent

HomeComponent

ngOnInit()
{
    console.log('loaded');
    this.retrieveData();
}

retrieveData()
{
    // this.dataService.getData().subscribe(...);
}

组件加载时我正在检索数据.当用户单击另一个routerLink(例如SettingsComponent)并返回到HomeComponent时,当然会再次调用该函数,因为该组件已重新加载.但是,每当我返回该组件时,它都会再次调用该函数,这会创建过多的不需要的HTTP请求.我需要防止这种情况,并确保仅在第一次调用该函数.我该怎么做呢?我应该使用其他组件生命周期挂钩吗?

I am retrieving data when the component loads. When the user clicks on another routerLink, for example, SettingsComponent and returns back to the HomeComponent, the function of course, is called again because the component has loaded again. But Everytime I return back to the component, it makes the function call again which creates too many unwanted HTTP requests. I need to prevent this and make sure the function is called only the first time. How do I do this? Should I use some other component lifecycle hook?

推荐答案

好的,我看到您使用的是

Okay I see you are using a service to load the data which is a good way.

然后,您可以简单地将数据缓存在某个位置,当您返回组件时,请检查该数据的缓存.我认为您可以将数据直接存储在服务中,从而将其保留在内存中,也可以将其放在

Then you can simply cache the data somewhere and when you come back to a component check the cache for this data. I think you can store the data directly in your service which will keep it in the memory or you can put it in the 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 -> 提供者

IMPORTANT: if using this approach you should make your service global when declaring it in 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方法

HomeComponenet

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 ...
    }
}

这两种方法都有一个局限性,那就是您不能处理大量数据,当然,如果您不想让正在使用您的应用程序的用户的浏览器崩溃:)

Both approaches has the limitation that you can't work with huge amounts of data, of course if you don't want to blow the browsers of users that are using your app :)

这篇关于我如何只在ngOnInit()上运行一个函数,而不是在从另一个routerLink返回时再次运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆