ngx-cookie
Implementation of Angular 1.x $cookies service to Angular. Successor of angular2-cookie
Table of contents:
Get Started
Installation
You can install this package locally with npm.
# To get the latest stable version and update package.json file: npm install ngx-cookie --save# or # yarn add ngx-cookie
After installing the library, it should be included in the SystemJS configurations.
/** * System configuration for Angular samples * Adjust as necessary for your application needs. * Taken from: https://github.com/angular/quickstart/blob/master/systemjs.config.js */ { System;}this;
Usage
CookieModule
should be registered in the AppModule
with forRoot()
static method and with forChild()
in the child modules.
These methods accepts CookieOptions
objects as well. Leave it blank for the defaults.
;; ; ;
;;
Angular Universal Usage
ngx-cookie
supports usage during Server Side Rendering (SSR / Angular Universal). Getting Server Side Rendering itself set up the first time can be tricky and is outside the scope of this guide. Here, we'll assume that you've got a working SSR setup similar to the Angular Universal Starter project, and you're just trying to get ngx-cookie
working with SSR.
Note: during normal, client side usage, ngx-cookie
manipulates the client cookies attached to the document
object. During SSR, ngx-cookie
will manipulate cookies in http request or response headers.
Setup
First up, edit app.server.module.ts
(located in root > src > app
of the Universal starter project) to overwrite ngx-cookie's CookieService
with ngx-cookie's CookieBackendService
during server side rendering.
/* app.server.module.ts */
import { CookieService, CookieBackendService } from 'ngx-cookie';
@NgModule({
imports: [
AppModule,
ServerModule,
ModuleMapLoaderModule,
],
bootstrap: [AppComponent],
providers: [{ provide: CookieService, useClass: CookieBackendService }], // <--- CHANGES * * * * *
})
export class AppServerModule {}
Next, we need to make providers for the 'REQUEST'
and 'RESPONSE'
objects created by the expressjs server during SSR. You can check out the CookieBackendService
code, but during SSR ngx-cookie
inject's these objects into CookieBackendService
. To do this, edit server.ts
(located in the root of the Universal Starter Project) to create providers for 'REQUEST'
AND 'RESPONSE'
.
/* server.ts */
// Find the call to res.render() in the file and
// update it with providers for 'REQUEST' and 'RESPONSE'
app.get('*', (req, res) => {
res.render('index', {
req: req,
res: res,
providers: [
{
provide: 'REQUEST', useValue: (req)
},
{
provide: 'RESPONSE', useValue: (res)
}
]
});
});
And that's it! all your application's calls to CookieService
should now work properly during SSR!
Examples
Here you can find some usage examples with popular boilerplate libraries.
Angular2-quickstart
A boilerplate provided by Angular team. (Link: https://github.com/angular/quickstart)
Just edit the systemjs.config.js
file and add the ngx-cookie
there.
/** * System configuration for Angular 2 samples * Adjust as necessary for your application needs. */this;
Angular2-seed
A popular seed project. (Link: https://github.com/mgechev/angular2-seed)
Add the following settings to the (constructor of) ProjectConfig
class (path: ./tools/config/project.config.ts
).
; this.addPackagesBundlesadditionalPackages;
Do not forget to inject the CookieModule
in the module AppModule
and SharedModule
.
CookieService
There are 7 methods available in the CookieService
(6 standard methods from Angular 1 and 1 extra removeAll()
method for convenience)
get()
Returns the value of given cookie key.
/** * @param * @returns */getkey: string: string;
getObject()
Returns the deserialized value of given cookie key.
/** * @param * @returns */getObjectkey: string: Object;
getAll()
Returns a key value object with all the cookies.
/** * @returns */getAll: any;
put()
Sets a value for given cookie key.
/** * @param * @param * @param */putkey: string, value: string, options?: CookieOptions: void;
putObject()
Serializes and sets a value for given cookie key.
/** * @param * @param * @param */putObjectkey: string, value: Object, options?: CookieOptions: void;
remove()
Remove given cookie.
/** * @param * @param */removekey: string, options?: CookieOptions: void;
removeAll()
Remove all cookies.
/** */removeAll: void;
Options
Options object should be a type of CookieOptions
interface. The object may have following properties:
- path - {string} - The cookie will be available only for this path and its sub-paths. By default, this is the URL that appears in your
<base>
tag. - domain - {string} - The cookie will be available only for this domain and its sub-domains. For security reasons the user agent will not accept the cookie if the current domain is not a sub-domain of this domain or equal to it.
- expires - {string|Date} - String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT" or a Date object indicating the exact date/time this cookie will expire.
- secure - {boolean} - If
true
, then the cookie will only be available through a secured connection. - httpOnly - {boolean} - If
true
, then the cookie will be set with theHttpOnly
flag, and will only be accessible from the remote server. Helps to prevent against XSS attacks. - storeUnencoded - {boolean} - If
true
, then the cookie value will not be encoded and will be stored as provided.