How to add expiry date to Angular 2 cookie. I am trying with Angular 2.0.0-beta.15. When i try to add options like below:
var expireDate = new Date (new Date().getTime() + (1000 * data.expires_in));
this._cookieService.put('token', this.token, {expires: expireDate});
above code throwing error like "[ts] Argument of type '{ expires: Date; }' is not assignable to parameter of type 'CookieOptionsArgs'.
Property 'path' is missing in type '{ expires: Date; }'. (local var)
expireDate: Date"
I can see on https://www.npmjs.com/package/angular2-cookie to override default options globally. I doubt if this is the method to add expiry date to cookie? Can somebody help me to understand more on this?
I have used this library with success: https://github.com/BCJTI/ng2-cookies. Use it like below with setting expiry date:
Include the lib:
import {Cookie} from 'ng2-cookies/ng2-cookies';
Set a cookie with expiry date of 365 days:
Cookie.setCookie("cookie-key", "cookie-value", 365);
A little bit late but Should be something like this
let key = 'testCookieKey';
let value = 'testCookieValue';
let opts: CookieOptionsArgs = {
expires: new Date('2030-07-19')
};
cookieService.put(key, value, opts);
Hope that
For Expiry date parameter in set cookies the value should be seconds to days calculation.
i.e. 2 min = (2/1440)
//use for 2 minutes....
auth-cookies.ts
import { Injectable } from '#angular/core';
import { Cookie } from 'ng2-cookies/ng2-cookies';
#Injectable()
export class AuthCookie {
constructor() { }
getAuth(): string {
return Cookie.get('id_token');
}
setAuth(value: string): void {
//0.0138889=20 minuts
//this accept day not minuts
//use for 20 minuts
Cookie.set('cookie_token', value, 0.0138889);
//use for 2 minuts
// Cookie.set('cookie_token', value,0.00138889)
}
deleteAuth(): void {
Cookie.delete('id_token');
}
}
i post it too late but hope this will be useful.
Related
whenever am i trying to remove cookie its show me this error.
TypeError: universal_cookie__WEBPACK_IMPORTED_MODULE_3__.default.remove is not a function
this is my code
Logout = () =>{
var user = Cookies.get('shailuKiCookie');
// console.log(user);
if(user){
Cookies.remove("shailuKiCookie");
// alert("logout successfully");
window.location.reload(false);
}else{
window.location.reload(false);
}
}
enter image description here
function set_cookie(name, value) {
document.cookie = name +'='+ value +'; Path=/;';
}
function delete_cookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
You don't have to specify a cookie value when you delete a cookie.
Just set the expires parameter to a past date:
note : HttpOnly cookies cannot be deleted with JavaScript on the client side.
you should create a Cookies object.
const cookies = new Cookies()
cookies.remove('cookie name')
I'm just need to make sure I have this correct. I don't have 30days (or even a day) to test this.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
I think all I have to do is add this line of code:
var days = "30";
Is this correct? How can I test that this works after 1 minute while still using the days var? I'm not very good at math :x
I can rest easy knowing everything is working.
I am testing every half-minute with the code below.
var days = "0.00034722222";
I user ion-datetime plugin.
All worked fine, till I tried to pass value to 'max' param.
I limit the date picker to 18 years ago.
The result is that when user open the datepicker, he see only years and days lists, if he want to select month - he need to 'pull' the month-list by scrolling.
Here is my code:
HTML:
<ion-datetime displayFormat="MMM DD, YYYY" [(ngModel)]="user.dob" [formControl]="birthdate" [max]="maxDob"></ion-datetime>
TypeScript:
export class SignUpPage {
maxDob: string;
signUpProfileForm: FormGroup;
birthdate: AbstractControl;
constructor(public fb: FormBuilder) { }
ngOnInit() {
var self = this;
self.signUpProfileForm= self.fb.group({
'birthdate': [],
});
self.maxDob = new Date(new Date().setFullYear(new Date().getFullYear() - 18)).toISOString();
}
}
P.S. if you are user with at list 1500 reputation, I will be happy if you will create new tag - "ion-datetime".
make Use of moment
export class Abc{
today:any;
mDate:any;
this.today = moment().format("YYYY-MM-DD");
let maxDate= new Date((new Date().getFullYear() - 18),new Date().getMonth(), new Date().getDate());
this.mDate=moment(maxDate).format("YYYY-MM-DD");
In HTML :
<ion-datetime displayFormat="DD/MMM/YYYY" [(ngModel)]="todo.date" max = "{{today}}" min="{{mDate}}"></ion-datetime>
I have set a cookie using the jQuery cookie plugin. I've set the expiration on the cookie to one hour, so after that time the cookie is deleted. I want to display the remaining time left until the cookie expires to the user by retrieving this info from the cookie itself. is this possible using the jQuery cookies plugin? If not is there an eloquent way to achieve this?
I've set the expiration in this way:
jQuery.cookie('Cookie', timedCookie, { expires: new Date(+new Date() + (60 * 60 * 1000)) });
It's impossible to get a cookie's expiration using JavaScript. The only way to do this would be to store the expiration date somehow, such as in a javascript variable or in another cookie or local storage.
Here's an example:
var MINUTES = 1000 * 60;
var expireTime = new Date(+new Date + (60 * MINUTES)); // store the expiration time
jQuery.cookie('Cookie', timedCookie, { expires: expireTime });
var updateMessage = function(msg){
document.getElementById('time-left').innerHTML = msg;
};
var i = setInterval(function(){ // calculate time difference every ~1 min
var timeLeft = expireTime - new Date;
if(timeLeft <= 0){
updateMessage('Your session has expired.');
clearInterval(i);
} else {
updateMessage('You have ' + (timeLeft / MINUTES | 0) + ' minute(s) left in your cookied session.');
}
}, MINUTES);
I want to disable a range of dates which I are fetched using Ajax. I'm doing it as follows -
$("#date_frm").datepicker({
dateFormat: 'yy-mm-dd',
constrainInput: true,
beforeShow:function(input, inst) {
$.ajax({
type: "POST",
url: "/admin/get_time_span",
data: "",
success: function(data) {
disabled_day = data;
},
});
},
beforeShowDay: disableRangeOfDays
});
function disableRangeOfDays(d)
{
//var arr = "2012-04-19 to 2012-04-26,";
var arr = disabled_day.split(",");
var arr = arr.split(",");
var cnt = arr.length-1;
for(i=0; i<cnt; i++) {
arr1 = arr[i].split(" to ");
//create date for from_date
frm_dt = arr1[0].split('-');
//create date for to_date
to_dt = arr1[1].split('-');
if(d >= new Date(frm_dt[0],(frm_dt[1]-1),frm_dt[2]) &&
d <= new Date(to_dt[0],(to_dt[1]-1),to_dt[2])) {
return [false];
}
}
return [true,''];
}
This works but not for the first time. When I open the date picker first time, the date range still selectable. But, after I close and reopen it, the date range is disabled. Also, if I change the month and come back to the current month then also it works. How can I disable the date range for the first time I open the date picker ? Also, for each month, I want to fetch the date ranges and disable them. How can I do this ?
After spending much time in checking possibilities, I fetched all the date ranges only once while loading the page and assigned all to a hidden field. I removed the Ajax call and used the value of the hidden field directly in the function disableRangeOfDays(d) and it worked as expected.