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.
Iam以某种方式扼杀了我的想法,将我的http共振数据保存了一周。如果数据较旧,那么1周我想开始一个新的http请求。
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.
现在我想将数据保存到localstorage一周。
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 :(
另外:我需要使用日期将数据保存到localstorage,然后检查存储的数据是否超过7天。但我不知道如何:(
3 个解决方案
#1
1
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.
请看看工作的plunker。在该演示中,我使用localStorage来存储项目列表以及获取这些项目的日期。请注意,由于在localStorage中获取和设置数据都返回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;
}
}
#2
0
You could set up a model inside your app that contains a piece of html data plus an expiry date, and then when the data is grabbed from the http request save it local storage using localStorage.set('key', data);
- they key could be some sort of user id if you have the ability for different users to log on to your app on the same device, or if not it could just be something that identifies this piece of data with the resource you are grabbing from your request.
您可以在应用程序中设置一个模型,其中包含一段html数据和一个到期日期,然后当从http请求中获取数据时,使用localStorage.set('key',data)保存本地存储; - 如果您能够让不同的用户在同一台设备上登录您的应用程序,那么它们的密钥可能是某种用户ID,或者如果不能,它可能只是用您从中获取的资源来识别此数据的内容你的申请。
So when a user then performs another request for that same data, first the localStorage is polled and the date from the data is checked against the current date - there are many ways to do this from the build in js Date class to libraries such as moment.js, and if the expiry date is still in the future, load the data with localStorage.get('key');
. If the expiry date has passed then you know the data is now out of date and you are free to request the data through http and start the cycle again.
因此,当用户然后对该相同数据执行另一个请求时,首先轮询localStorage并根据当前日期检查数据中的日期 - 有很多方法可以从js Date类中的构建到诸如moment之类的库.js,如果到期日仍在将来,请使用localStorage.get('key');加载数据。如果到期日期已过,那么您知道数据现在已过期,您可以通过http请求数据并再次开始循环。
#3
0
just add timeout
which will set ExerciseData.data
to null and call it in getExerciseList()
after if()
.
只需添加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); // ...
To be more precise, you should add it to the Promise, when you have your data. For example after resolve(this.data);
getExerciseList():any {if(this.data){return Promise.resolve(this.data); } timeout(()=> {this.data = null;},7 * 24 * 60 * 60 * 1000); // ...更确切地说,当你有数据时,你应该将它添加到Promise中。例如在resolve(this.data)之后;
So this is a question about cookies, not http response caching.
所以这是关于cookie的问题,而不是http响应缓存。
If you don't know how to use cookies, use something like https://www.npmjs.com/package/ng2-cookies and set expiration time to 7 days, so when you read cookie in 7 days it will be empty and you get data from server.
如果您不知道如何使用cookie,请使用https://www.npmjs.com/package/ng2-cookies之类的内容并将过期时间设置为7天,因此当您在7天内阅读cookie时,它将为空你从服务器获取数据。
#1
1
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.
请看看工作的plunker。在该演示中,我使用localStorage来存储项目列表以及获取这些项目的日期。请注意,由于在localStorage中获取和设置数据都返回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;
}
}
#2
0
You could set up a model inside your app that contains a piece of html data plus an expiry date, and then when the data is grabbed from the http request save it local storage using localStorage.set('key', data);
- they key could be some sort of user id if you have the ability for different users to log on to your app on the same device, or if not it could just be something that identifies this piece of data with the resource you are grabbing from your request.
您可以在应用程序中设置一个模型,其中包含一段html数据和一个到期日期,然后当从http请求中获取数据时,使用localStorage.set('key',data)保存本地存储; - 如果您能够让不同的用户在同一台设备上登录您的应用程序,那么它们的密钥可能是某种用户ID,或者如果不能,它可能只是用您从中获取的资源来识别此数据的内容你的申请。
So when a user then performs another request for that same data, first the localStorage is polled and the date from the data is checked against the current date - there are many ways to do this from the build in js Date class to libraries such as moment.js, and if the expiry date is still in the future, load the data with localStorage.get('key');
. If the expiry date has passed then you know the data is now out of date and you are free to request the data through http and start the cycle again.
因此,当用户然后对该相同数据执行另一个请求时,首先轮询localStorage并根据当前日期检查数据中的日期 - 有很多方法可以从js Date类中的构建到诸如moment之类的库.js,如果到期日仍在将来,请使用localStorage.get('key');加载数据。如果到期日期已过,那么您知道数据现在已过期,您可以通过http请求数据并再次开始循环。
#3
0
just add timeout
which will set ExerciseData.data
to null and call it in getExerciseList()
after if()
.
只需添加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); // ...
To be more precise, you should add it to the Promise, when you have your data. For example after resolve(this.data);
getExerciseList():any {if(this.data){return Promise.resolve(this.data); } timeout(()=> {this.data = null;},7 * 24 * 60 * 60 * 1000); // ...更确切地说,当你有数据时,你应该将它添加到Promise中。例如在resolve(this.data)之后;
So this is a question about cookies, not http response caching.
所以这是关于cookie的问题,而不是http响应缓存。
If you don't know how to use cookies, use something like https://www.npmjs.com/package/ng2-cookies and set expiration time to 7 days, so when you read cookie in 7 days it will be empty and you get data from server.
如果您不知道如何使用cookie,请使用https://www.npmjs.com/package/ng2-cookies之类的内容并将过期时间设置为7天,因此当您在7天内阅读cookie时,它将为空你从服务器获取数据。