Fargho Fargho - 3 months ago 12
TypeScript Question

Typescript: Save http response for a limited amount of time

at the moment iam working on my first typescript app.

Iam struggeling somehow with my idea to save my http resonse data for 1 week. If the data is older then 1 week i want to start a new http request.

at the moment i just store my data in a variable, my code looke like this:

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);
});
});
}
}


Now i want to save the data to the localstorage for 1 week.

Whats the best way to archive that?

Do i also need to touch the constructor?

Addition: I need to save the data to localstorage with a date and then check, if the stored data is older than 7 days. But i dont know how :(

Answer

Please take a look at working plunker. In that demo, I use localStorage to store the list of items and also the date when those items were obtained. Please notice that since both getting and setting data in the localStorage returns a Promise, we need to use the then((result) => {...}) method to work with those values.

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;

  }
}
Comments