简体   繁体   English

缓存angular2 Html页面及其ngOnInit方法

[英]caching angular2 Html pages and its ngOnInit method

I am working on tabs in my angular2 web app.I have three tabs containing user profile information. 我正在使用angular2 web应用程序中的选项卡。我有三个包含用户配置文件信息的选项卡。

1st Tab contain user personal info for that data I am calling an API 第一个选项卡包含我称之为API的数据的用户个人信息

2nd Tab contain user subscription info that is also coming form API 第二个选项卡包含也来自API的用户订阅信息

But problem I am facing is when I change the tab my api are getting called every time.which is not proper. 但我面临的问题是,当我改变标签时,我的api每次都会被调用。这是不合适的。

I have use both this 我已经使用了这两个

.share() and .cache()

method and also written my code in ngOnInit function but still the same my api's are getting called whenever I change the tab. 方法,并在ngOnInit函数中编写我的代码,但每当我更改选项卡时仍然会调用我的api。 Can anyone please help me out to cache the view or its ngOnInit method. 任何人都可以帮我缓存视图或其ngOnInit方法。

Maybe it is too late. 也许为时已晚。 But a easy way to keep a cache from your component during all the life-cycle of a Angular2 app is using a storage variable in your service. 但是,在Angular2应用程序的整个生命周期中,在组件中保留缓存的一种简单方法是在服务中使用存储变量。

 private myObject:any; constructor(private _dataService: DataServiceService) { } ngOnInit() { //Recover Cache from the servicies // IF cache==null THEN getAPI // ELSE get chache from the service if(this._dataService.storage["myObject"] == null){ this.getMyObject(); }else{ this.myObject = this._dataService.storage["myObject"]; } } ngOnDestroy(){ // STORE CACHE in the service BEFORE DESTROY the COMPOMENT this._dataService.storage["myObject"] == null ? this._dataService.storage["myObject"] = this.myObject : this.myObject = this._dataService.storage["myObject"]; } getMyObject(){ this._dataService.getAPI("YOURAPI").subscribe( (p:any)=>this.myObject = p, (error) => console.log(error) ); } 

  public storage; constructor(private http: Http) { this.storage ={}; } 

So, I assume that you cont want to call the API call every time you change between components, It works for me. 因此,我假设您每次在组件之间进行更改时都要调用API调用,它对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM