有没有一种方法可以保存HTTP响应数据以便不调用HTTP服务?

时间:2019-03-24 11:46:14

标签: javascript angular typescript http ionic-framework

我会尽力解释,这是我有史以来第一个Ionic应用程序。

我的目标是创建一个简单的仪表板,其中包含从JSON文件中提取的某些类别,并调用Cordova HTTP本机服务。 单击仪表板中的某个类别时,它应根据我通过[routerLink]指令发送的特定ID参数为类别加载另一个仪表板。

它可以按预期工作,但是当我点击“后退”按钮并返回主仪表板时,如果单击同一类别,则会触发ngOnInit()方法,并且http服务再次获取数据。

如果尚未提取特定的类别数据,我想单击一个类别并仅在第一次调用http服务,而在第二次单击该类别时仅显示该数据。

我已经尝试检查this.category_sources,但是每次我点击“后退”按钮时,该组件都被破坏了,数据丢失了。

  ngOnInit() {
    this.retrieveID();
    console.log("OnInit");
    this.presentLoading();
    this.CategoryCtrl();
  }

  retrieveID() {
    this.sub = this.route.params.subscribe(params => {
      this.id = +params['id'];
    });
  }

  CategoryCtrl() {
    if (this.category_sources) {
      console.log("Data already existing");
      this.stopLoading();
    } else {
    this.serverService.getReviewsCategory(this.id)
    .subscribe((data) => {
      this.fetched = true;
      this.category_sources = data['reviews'];
      this.info = data['info'];
      this.banner = data['banner'];
      this.fetched = true;
      this.stopLoading();
    });
  }
}

  backClicked() {
    console.log("Back clicked");
    this.location.back();
  }

  async presentLoading() {
    const loadingController = this.loadingController;

    const loadingElement = await loadingController.create({
      spinner: 'crescent',
    });
    return await loadingElement.present()
  }

  async stopLoading() {
    return await this.loadingController.dismiss();
  }

}

2 个答案:

答案 0 :(得分:1)

我有主意,您可以使用:单击成功后(设置,获取)数据,保存localStorage let data = localStorage.setItem('categories'); let data = localStorage.getItem('categories');

//FRONT-END ANGULA

categories:any={}

Constructor(){
  //check categories localStorage
  let dataCatogories = localStorage.getItem('categories');
  if(dataCatogories.length>0){
  
    //You can handle it here 
    this.categories = dataCategories;
  }

}


//CLick categories
getAllCatogories = ()=>{
  this.http.get('APP_URL').subscribe(item=>{
   localStorage.setItem("categories",item);
  }

}

答案 1 :(得分:1)

您可以创建一个全局服务来处理无需本地存储的缓存,而只需将数据保存在内存(对象)中,这样当应用关闭时,数据将消失

CashingService

@Injectable({ providedIn: "root"})
export class CashingService {

  private __cach = {}
  isCashed(url: string) {
    return this.__cach[url];
  }

  getData(url: string) {
    return this.__cach[url]
  }

  setData(url) {
    return (data) => {
      if (data && (data instanceof Error) === false)
        this.__cach[url] = data
    };

  }

  reset() {
    this.__cach = {};
  }
}

实施服务

@Injectable()
export class ServerService {

  constructor(private http: HttpClient , private _c:CachingService ) { }

  public getReviewsCategory(url: any): Observable<any> {

    if (this._c.isCashed(url)){
     return of(this._c.getData(url));
    } else {
    return this.http.get(url)
      .pipe(
       tab(this._c.setData(url)),
       catchError(this.handleError('apiGetRequest'))
      );
    }

  }
}

从服务中获取数据

组件✨

  ngOnInit() {
    this.retrieveID();
    console.log("OnInit");
    this.presentLoading();
    this.CategoryCtrl();
  }

  CategoryCtrl() {

    this.serverService.getReviewsCategory(this.id)
    .subscribe((data) => {
      this.category_sources = data['reviews'];
      this.info = data['info'];
      this.banner = data['banner'];
      this.fetched = true;
      this.stopLoading(); // stop the spinner
    });
  }
}

您可以查看有关rxjs之类的不同方式的答案,以处理How to perform caching http get request in angular 5?

相关问题