javascript - 有没有办法保存 HTTP 响应数据,以便不召回 HTTP 服务?

标签 javascript angular typescript http ionic-framework

我会尽力解释,这是我的第一个 Ionic 应用程序。

我的目标是创建一个简单的仪表板,其中包含从 JSON 文件中获取的一些类别,调用 Cordova HTTP native 服务。 单击仪表板中的一个类别时,它应该加载另一个仪表板,其中包含基于我通过 [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();
  }

}

最佳答案

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

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 等不同方式处理 chaching 的答案 How to perform caching http get request in angular 5?

关于javascript - 有没有办法保存 HTTP 响应数据,以便不召回 HTTP 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55323457/

相关文章:

javascript - React-Router - 将方法传递给子组件

javascript - Python/Flask/HTML - 在新窗口而不是主页中呈现 HTML

javascript - 在 Iframe 中跟踪鼠标移动的问题

typescript - 错误 "Cannot use ' new',表达式类型缺少调用或构造签名。”导入 Esri 类型时

javascript - IFRAME 中的 PHP 脚本会阻止其他代码

node.js - Angular 2多次错误TS2300 : Duplicate identifier

angular - ngrx 中的 reducer 和不变性

css - 通过内部组件 angular2 添加 css 文件

javascript - 如何在 Angular 5 中从 Typescript 调用 JavaScript 函数?

AmCharts 的 TypeScript 声明