I'm utilizing the "ngx-cookie-service" to work with cookies in my angular project.
I have sumpled across an issue where I check if a cookie exists, if it === false then it should retrieve data from an API, but on the first run it always returns false due to the cookie not existing, but the JSON
is not retrieved as seen in this picture.
After another reload it then shows that the cookie exists and retrieves the data successfully as seen in this image.
I'm very confused why it doesn't print the JSON
in the first request, but does it in any request following.
Here is my typescript code.
let cookieExists: boolean = this.cookieService.check(this.id);
console.log("Cookie exists: " + cookieExists);
if (cookieExists === false) {
axios.get('https://localhost:5001/api/Trace/' + this.id)
.then((response: AxiosResponse<Trace>) => {
var minutesToAdd = 1;
var currentDate = new Date();
var futureDate = new Date(currentDate.getTime() + minutesToAdd * 60000);
this.cookieService.set(this.id, JSON.stringify(response.data), futureDate, null, null, null, null);
});
}
console.log(this.cookieService.get(this.id));
Upon the initial request, the data should be printed in the console, just like in the second image.
Async code that I have tried, with the same result.
let cookieExists: boolean = this.cookieService.check(this.id);
console.log("Cookie exists: " + cookieExists);
if (cookieExists === false) {
const doGetRequest = async () => {
await axios.get('https://localhost:5001/api/Trace/' + this.id)
.then((response: AxiosResponse<Trace>) => {
var minutesToAdd = 1;
var currentDate = new Date();
var futureDate = new Date(currentDate.getTime() + minutesToAdd * 60000);
this.cookieService.set(this.id, JSON.stringify(response.data), futureDate, null, null, null, null);
});
};
doGetRequest();
}
console.log(this.cookieService.get(this.id));