bcjti / ng2-cookies Goto Github PK
View Code? Open in Web Editor NEWSimple library to deal with cookies in Angular2
Simple library to deal with cookies in Angular2
I did like instruction says and have following error:
Error: XHR error (404 Not Found) loading http://localhost/ng2-cookies/ng2-cookies
great work on ng2-cookies!
I want to use it, but i get an error
ParseError: 'import' and 'export' may appear only with 'sourceType: module'
Same happen on this project:
urish/ngx-moment#33
The latest npm package 1.0.12
is missing the default cookie path from this commit.
Hi,
could you perhaps update src/services/cookie.d.ts so that it supports Secure parameter? (not yet sure how to "properly" fix it myself, i would have asked for pull request myself)
Thanks for the script btw!
Hey Guys,
Could it be that your library only takes the last 'set-cookie' object from the header?
I've discovered the following problem: The response header from the login function of the site I'm calling has two set-cookie objects:
set-cookie:id=c90ee0f20c1ef9c5995894321a6dc518
set-cookie:ict-lb-oracle=orab1
But If i'm calling Cookie.getAll()
, i only get the second cookie. Can i do anything to fix it?
Kind Regards,
Matthias
The current version on npm is outdated and causes some problems with the latest build systems (webpack 3+), can we publish a new version with the latest changes?
Hi there,
This does not seem to work in safari.
Is there a way to set various options like 'HttpOnly' and 'Secure' on a cookie with this library?
Please update the examples to include the date, path and domain options. I will happily do this but can't readily figure out how to edit the wiki directly. Thanks!
I'm having an issue where certain routes of my application have multiple cookies by the same name. This only happens on certain routes, when you navigate away from them the duplicate cookie (with a different value in my case) disappears.
I've looked through the source code and set() just applies the cookie using document.cookie
which I don't believe checks for duplicates, however when I attempted to apply duplicates intentionally calling set() twice with different values, only the latest value persisted.
I can't figure out if this is a common issue (no other issues mention it) and if delete() needs to be called prior to updating the cookie value. I'm also not sure why it only occurs on a single route when the a path argument isn't passed when calling set().
Please update your README. Change npm install ng2-cookies to npm install ng2-cookies --save in order to save this package in package.json.
This method not work . http://prntscr.com/e602nz
Importing the Cookie class and trying to do a check causes an Error:
import { Cookie } from 'ng2-cookies/ng2-cookies'
Cookie.check('cookName')
Error in web pack build:
Property 'check' does not exist on type 'typeof Cookie'
Set and Gets do not work as well, as there is nothing in the dev console or storage of the newly created (attempted) cookies.
Tried some tests:
Cookie.check('searchTerm')
if(!Cookie.get('searchTerm')){
Cookie.set('searchTerm', term)
}
if(!Cookie.get('searchActive')){
Cookie.set('searchActive', 'true')
}
None of these tests have work as of yet.
When attempting to provide a component with a mock for CookieService, it never gets injected correctly.
Example:
class CookieServiceMock {
check = jasmine.createSpy('check').and.returnValue(true);
setMock = jasmine.createSpy('set');
delete = jasmine.createSpy('delete');
}
describe('assessments-certs.component', function () {
let fixture: ComponentFixture<AssessmentsAndCertsComponent>;
let comp: AssessmentsAndCertsComponent;
let cookieSvcMock: CookieServiceMock;
beforeEach(async(() => {
cookieSvcMock = new CookieServiceMock();
TestBed.configureTestingModule({
declarations: [
AssessmentsAndCertsComponent,
CertificateComponentMock
],
providers: [
{
provide: CookieService,
useValue: cookieSvcMock
}
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
}));
Component (partial code):
@Component({
selector: 'assessments-certs',
providers: [CookieService],
templateUrl: './assessments-certs.component.html'
})
export class AssessmentsAndCertsComponent {
constructor(private _cookieSvc: CookieService) {
}
...
}
Result: _cookieSvc always injects as CookieService(), and not the actual mock. I suspect this is because the CookieService class lacks the @Injectable decorator.
If i tried to set cookie value as below
Cookie.setCookie('isAuthenticated', true);
I am getting this error:
error TS2345: Argument of type 'boolean' is not assignable to parameter of type 'string'.
How to fix this issue?
I'm getting this error when I use Cookie.getAll()
but it works onCookie.get()
.
Sample Text: Tōkyō-to
I gave the expiration some minutes from now and it did not get expired.
I added the lib to a fresh Angular project generated using angular-cli
. There was no need to change any configuration files as mentioned in README.MD
file.
Issuing this command in the project root is enough to add the library:
npm install ng2-cookies --save
Hello. I'm getting the following error when I use your project in the standard angular 2 quick start demo. I'm using the dependency in npm. My package.json file has "ng2-cookies": "^0.1.4"
referenced.
Uncaught SyntaxError: Unexpected token <
I've tried importing the module in the index.html
<script src="node_modules/ng2-cookies/ng2-cookies.js"></script>
In the actual service component. I'm importing it as suggested in your readme.
import {Injectable} from 'angular2/core';
import {Cookie} from 'ng2-cookies/ng2-cookies';
@Injectable()
export class AuthenticationService {
logoutUser() {
let csrfcookie = Cookie.getCookie('csrftoken');
}
}
I can't seem to fix the issue. Any help would be appreciated. Thank you!
Stack trace:
Error encountered resolving symbol values statically. Only initialized variables and constants can be referenced because the value of this variable is needed by the template compiler (position 49:22 in the original .ts file), resolving symbol Cookie in node_modules/ng2-cookies/cookie.d.ts
at positionalError (/opt/atlassian/pipelines/agent/build/node_modules/@angular/compiler/bundles/compiler.umd.js:25730:39)
at simplifyInContext (/opt/atlassian/pipelines/agent/build/node_modules/@angular/compiler/bundles/compiler.umd.js:25567:31)
at StaticReflector.simplify (/opt/atlassian/pipelines/agent/build/node_modules/@angular/compiler/bundles/compiler.umd.js:25581:17)
at StaticReflector.annotations (/opt/atlassian/pipelines/agent/build/node_modules/@angular/compiler/bundles/compiler.umd.js:25077:64)
at NgModuleResolver.resolve (/opt/atlassian/pipelines/agent/build/node_modules/@angular/compiler/bundles/compiler.umd.js:17557:86)
at CompileMetadataResolver.getNgModuleMetadata (/opt/atlassian/pipelines/agent/build/node_modules/@angular/compiler/bundles/compiler.umd.js:18058:64)
at addNgModule (/opt/atlassian/pipelines/agent/build/node_modules/@angular/compiler/bundles/compiler.umd.js:24839:62)
at ./node_modules/@angular/compiler/bundles/compiler.umd.js:24850:18
at Array.forEach (native)
at _createNgModules (/opt/atlassian/pipelines/agent/build/node_modules/@angular/compiler/bundles/compiler.umd.js:24849:30)
Compilation failed
Seems like the breaking change was introduced after [email protected]
Please give me a suggestion how to stop url encoding in cooking when i used to store as key value pair.
for ex; i am setting key as 'somepath' and value as '/path/path2/path3' after when i am looking inside browser it is different from actual value it is like %2Fpath%2F% something like this.
Please help me to resolve this.
Hi,
nice library :) there is only one issue - you use window.escape which is deprecated (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape). For example there is no way to save an array to cookie with your library :(
Greetings!
Cookie.deleteAll() not working
Is there a specific reason your class won't delete a cookie if it has no value? I have a use case to delete a cookie that has no value.
Cheers,
Rob C
It is possible to get value expires
or create
from a cookie with this library?
This information of print for example:
I noticed is only possible with the library to get the value of the Content
attribute of the print.
It is currently commented in the ".npmignore" file, and the node packager installs all .ts files which confuses "tsc"
Can you add a function to check if cookies enabled in browser
I'm working from this seed https://github.com/AngularClass/angular2-webpack-starter, and I keep getting these warnings. Is there something I'm missing?
I notice the npm install brings .d.ts files and does not include the .ts files. I'm new to webpack, so I'm not sure If I'm missing something.
It works perfectly if I install from github.
WARNING in ./~/ng2-cookies/ng2-cookies.js
Cannot find source file 'ng2-cookies.ts': Error: Cannot resolve 'file' or 'directory' ./ng2-cookies.ts in /home/dev/code/app/node_modules/ng2-cookies
WARNING in ./~/ng2-cookies/src/services.js
Cannot find source file 'services.ts': Error: Cannot resolve 'file' or 'directory' ./services.ts in /home/dev/code/app/node_modules/ng2-cookies/src
WARNING in ./~/ng2-cookies/src/services/cookie.js
Cannot find source file 'cookie.ts': Error: Cannot resolve 'file' or 'directory' ./cookie.ts in /home/dev/code/app/node_modules/ng2-cookies/src/services
Hey,
currently all Methods contain the word Cookie
in it.
Example: .deleteCookie
, .setCookie
, ...
I think it would be better when you only call .delete
, .set
, .get
Reason: When you use Cookie.setCookie
, the second Cookie is not really necessary and I would be shorter.
Please provide delete all cookie option
I really liked your project and I was trying to use it through a WebJar inside a Scala application. The page automatically create a jar
ready to be used based on the npm
package.
The problem with ng2-cookies
is that when the WebJar is being deployed, it requires the package to have a supported license (MIT is supported) and it is not finding any license file on GitHub or inside the package.json
.
Hey guys. This is only a suggestion.
I needed to use Cookies in my app so I looked for something on npm. At first a came to this repo, but in my app I need to set the Cookie expiration to a precise date and time (even seconds). And then I realized this package only allows for setting the expiration using a delta set in days. And this prevented me from using this repo.
Currently I have implemented what I needed using angular2-cookie. But I just wanted to leave the suggestion for you guys that you allow for setting the expiration date using a Date object, with seconds precision.
Hi,
I'm having a issue with Cookie.deleteAll();
. It's not cleaning my cookie. Anyont with the same issue?
My component:
import { Cookie } from 'ng2-cookies/ng2-cookies';
...
@Injectable()
export class CookieService {
...
signOut():boolean {
Cookie.deleteAll();
return true;
}
}
the typings for set does not have the parameter of acceptance for Secure.
I'm wondering if you have a solution for my problem.
I'm using the library defining 2 cookies : one called access token and the other called refresh token.
I store inside the cookies tokens retrieved in a json after an http.post on an auth server.
I'm trying to implement the refreshing of the token but the async behave of the http calls is giving me some problem.
Here's the code:
getRefresh Function
getRefresh(token){
let params = new URLSearchParams();
params.append('grant_type','refresh_token');
params.append('refresh_token',token);
params.append('client_id','web_app');
let headers = new Headers({'Content-type': 'application/x-www-form-urlencoded; charset=utf-8','Authorization': 'Basic '+btoa("web_app:")});
let options = new RequestOptions({headers: headers});
return this._http.post('http://localhost:9997/oauth/token',params.toString(),options)
.map(res => res.json())
.subscribe(
data => {
this.saveToken(data)
});
}
saveToken Function
saveToken(token){
var expireDate = 0.00034722222;
//var expireDate = token.expires_in;
Cookie.set("access_token", token.access_token, expireDate);
Cookie.set("refresh_token", token.refresh_token, 1);
this._router.navigate(['/']);
}
getResource Function
getResource(resourceUrl): Observable<any> {
var cookie;
cookie = Cookie.get("access_token");
var headers = new Headers({
'Content-type': 'application/x-www-form-urlencoded; charset=utf-8',
'Authorization': 'Bearer ' + cookie
});
var options = new RequestOptions({headers: headers});
return this._http.get(resourceUrl, options)
.map((res: Response) => res.text())
.catch((error: any) => Observable.throw(error().json().error || 'Server error'));
}
Everything starts from the main component that call the service via event bound to a button.
How can i resolve?
Trying to do this.cookieService.delete('authToken');
in a login.service
but it doesn't delete.
deleteAll()
doesn't work either.
But injecting cookieService
in component works.
Any idea?
Cookie names are encoded using encodeURIComponent
making it impossible to set a valid cookie name with certain characters, specifically #
. This is important when writing code to set cookie names matching unchangeable legacy systems and established system standards.
I am using ng2-Cookie for storing token value and using this cookie in different angular components by importing it. When clicking on logout button (logout method placed in navbar component) from anywhere (different states like home, account, managers components) in the application it's redirecting to the login page(login component) in Chrome and Firefox (working fine) browsers. But it's not working properly in IE browser.
In IE, if logout event fired from home page (homecomponent.ts file, starting of the application after immediate login) then only application is logging out.
And when clearing the cookies of the browser application is redirecting to the login page in Firefox and Chrome browsers but not working as expected in IE browser.
Below is the code I am using
navbar.component.ts
Logout() {
Cookie.deleteAll();
this._router.navigate(['/login']);
}
login.component.ts
ngOnInit() {
let token = Cookie.get('auth_token');
if (token != null && token != undefined && !this._roleauth.isTokenExpired(token)) {
this._router.navigate(['/home']);
}
}
Is it the behavior of ng2-cookie in IE browser? or am I doing in wrong way? Can anyone please help me with this.
When i set cookie with
Cookie.delete('cookname'); or Cookie.set('cookname', null);
cookie become to string 'null' not null value.
Hi,
how is this related with angular2? It's just a Cookie wrapper implementation..
(just a question)
grtz
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.