打字稿:在有限的时间内保存http响应

Typescript: Save http response for a limited amount of time

目前我正在开发我的第一个打字稿应用程序。

我正在为将我的 http 响应数据保存 1 周的想法而苦苦挣扎。如果数据早于 1 周,我想启动一个新的 http 请求。

目前我只是将数据存储在一个变量中,我的代码如下所示:

export class ExerciseData {
  data: any;

  constructor(private http: Http) {
  }

  getExerciseList(): any {
    if (this.data) {
      return Promise.resolve(this.data);
    }

    return new Promise(resolve => {
      this.http.get('https://test.test/api-exercise-v1/')
          .map(res => res.json())
          .subscribe(data => {
            this.data = data;
            resolve(this.data);
          });
    });
  }
}

现在我想将数据保存到localstorage 1周。

存档的最佳方式是什么?

我还需要接触构造函数吗?

补充: 我需要将数据保存到 localstorage 并指定日期,然后检查存储的数据是否超过 7 天。但我不知道如何:(

只需添加 timeout 即可将 ExerciseData.data 设置为 null 并在 if() 之后的 getExerciseList() 中调用它。

getExerciseList(): any { if (this.data) { return Promise.resolve(this.data); } timeout(() => { this.data = null; }, 7*24*60*60*1000); // ... 更准确地说,当您拥有数据时,您应该将其添加到 Promise 中。 例如在 resolve(this.data);

之后

所以这是关于 cookie 的问题,而不是 http 响应缓存。

如果您不知道如何使用 cookie,请使用 https://www.npmjs.com/package/ng2-cookies 之类的东西并将过期时间设置为 7 天,这样当您在 7 天内读取 cookie 时它将为空并且您从服务器获取数据.

您可以在您的应用程序中设置一个模型,其中包含一段 html 数据和一个到期日期,然后当从 http 请求中获取数据时,使用 [=10= 将其保存在本地存储中] - 如果您有能力让不同的用户在同一台​​设备上登录您的应用程序,它们的关键可能是某种用户 ID,或者如果没有,它可能只是用您正在获取的资源标识这段数据的东西根据您的要求。

因此,当用户随后对同一数据执行另一个请求时,首先会轮询 localStorage,然后根据当前日期检查数据中的日期 - 有很多方法可以通过 js Date class 到 moment.js 等库,如果到期日期还在未来,则加载数据 localStorage.get('key');。如果到期日期已过,则您知道数据现在已过时,您可以自由地通过 http 请求数据并重新开始循环。

请看working plunker。在该演示中,我使用 localStorage 来存储项目列表以及获得这些项目的日期。请注意,由于在 localStorage returns 中获取和设置数据都是一个 Promise,我们需要使用 then((result) => {...}) 方法来处理这些值。

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import { Storage, LocalStorage } from 'ionic-angular/index';
import 'rxjs/Rx';

@Injectable()
export class DataService {

  constructor(private http:Http) {
    this.local = new Storage(LocalStorage);
  }

  getExerciseList(): any {

    return new Promise(resolve => {

      // Check if we have the list in the local storage
      this.local.get('ExerciseList').then((list) => {
        if(list) {
          // We have a list, so we try to find out the date
          this.local.get('ExerciseListDate').then((date) => 
          {
            if(date && this.newerThanAWeek(date)) {
              // The data is valid, so we don't do the http request
              console.log("Data retrieved from localStorage");
              resolve(JSON.parse(list));
            } else {
              // Data is old, so we make the Http request
              this.http.get('https://jsonplaceholder.typicode.com/users')
                  .map(res => res.json())
                  .subscribe(listDataFromServer => {
                    console.log("Return HTTP Request");
                    // Save this information to use it later                     
                    this.saveInfoInLocalStorage(listDataFromServer).then(() => {
                      // Data is saved now, so we can send it to the user
                      resolve(listDataFromServer);
                    });
                  });
            }
          });
        } else {
            // We don't have the list stored so we make the Http request
            this.http.get('https://jsonplaceholder.typicode.com/users')
                .map(res => res.json())
                .subscribe(listDataFromServer => {
                  console.log("Return HTTP Request");
                  // Save this information to use it later                      
                  this.saveInfoInLocalStorage(listDataFromServer).then(() => {
                    // Data is saved now, so we can send it to the user
                    resolve(listDataFromServer);
                  });
                });
        }
      });
    });
  }

  public saveInfoInLocalStorage(data: Array<any>) {
    // Save the list first
    return this.local.set('ExerciseList', JSON.stringify(data)).then(() => {
      // Now we set the date
      this.local.set('ExerciseListDate', new Date());
    });
  }

  public newerThanAWeek(storedDateStr: string) {
    let today = new Date();
    let storedDate = new Date(storedDateStr);
    let timeDiff = Math.abs(today.getTime() - storedDate.getTime());
    let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 

    if(diffDays < 7) {
      return true;
    }
    return false;

  }
}