缓存angular2的Html页面及其ngOnInit方法



我正在我的angular2 web应用程序的标签。我有三个标签包含用户配置信息。

第一个选项卡包含用户个人信息的数据,我正在调用API

第二个选项卡包含来自API的用户订阅信息

但我面临的问题是,当我改变标签我的api每次都被调用。这是不合适的。

我用过这两个

.share() and .cache()

方法,也写了我的代码在ngOnInit函数,但仍然是相同的我的api的被调用,每当我改变标签。谁能帮我缓存视图或它的ngOnInit方法?

也许太晚了。但是,要想在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 ={};
   }

所以,我假设你不希望每次在组件之间进行更改时调用API调用,它适用于我。

最新更新