当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

angular2-cookie

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 林建本
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

angular2-cookie DEPRECATED => ngx-cookie

This library is deprecated and please use ngx-cookie instead.

Implementation of Angular 1.x $cookies service to Angular 2 v1.2.6

Please use >=1.2.4 for Angular >2.0.0, 1.1.x versions for beta, 1.2.2 version is for release candidates earlier than rc.5 and 1.2.3 is for >rc.5.

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 angular2-cookie --save

After installing the library, it should be included in the SystemJS configurations.

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 * Taken from: https://github.com/angular/quickstart/blob/master/systemjs.config.js
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs':                       'npm:rxjs',
      'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
      'angular2-cookie':            'npm:angular2-cookie'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular2-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      },
      'angular2-cookie': {
        main: './core.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);

Usage

CookieService class is an injectable service with angular @Injectable() decorator. Therefore, it needs to be registered in the providers array (encouraged way).Then, it will be available in the constructor of the component class.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { CookieService } from 'angular2-cookie/services/cookies.service';

import { AppComponent }  from './app.component';

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppComponent ],
  providers: [ CookieService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
import {Component} from 'angular2/core';
import {CookieService} from 'angular2-cookie/core';

@Component({
    selector: 'my-very-cool-app',
    template: '<h1>My Angular2 App with Cookies</h1>'
})

export class AppComponent { 
  constructor(private _cookieService:CookieService){}
  
  getCookie(key: string){
    return this._cookieService.get(key);
  }
}

Universal Support

This module supports angular universal through angular service overrides, make sure you add something likethe following to your backend module instead of adding the CookieService provider

import { NgModule }      from '@angular/core';
import { UniversalModule } from 'angular2-universal';

import { CookieService } from 'angular2-cookie/services/cookies.service';
import { CookieBackendService } from 'angular2-cookie/services/cookies.backend.service';

import { AppComponent }  from './app.component';

@NgModule({
  imports: [ UniversalModule ],
  declarations: [ AppComponent ],
  providers: [
  	{
      provide: CookieService,
      useClass: CookieBackendService
    }
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

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 angular2-cookie there.

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs':                       'npm:rxjs',
      'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
      'angular2-cookie':            'npm:angular2-cookie'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular2-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      },
      'angular2-cookie': {
        main: './core.js',
        defaultExtension: 'js'
      }
    }
  });
})(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).

/* Add to or override NPM module configurations: */
//this.mergeObject( this.PLUGIN_CONFIGS['browser-sync'], { ghostMode: false } );
this.mergeObject(this.SYSTEM_CONFIG_DEV['paths'], {'angular2-cookie': 'node_modules/angular2-cookie/bundles/angular2-cookie.js'});
this.mergeObject(this.SYSTEM_BUILDER_CONFIG['packages'], {
  'angular2-cookie': {
    main: 'core.js',
    defaultExtension: 'js'
  }
});

Do not forget to inject the service in the module (providers array).

Angular-cli

A CLI tool for Angular2.(Link: https://github.com/angular/angular-cli)

Edit the vendorNpmFiles array (path: ./angular-cli-build.js).

// Angular-CLI build configuration
// This file lists all the node_modules files that will be used in a build
// Also see https://github.com/angular/angular-cli/wiki/3rd-party-libs

/* global require, module */

var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      'systemjs/dist/system-polyfills.js',
      'systemjs/dist/system.src.js',
      'zone.js/dist/**/*.+(js|js.map)',
      'es6-shim/es6-shim.js',
      'reflect-metadata/**/*.+(ts|js|js.map)',
      'rxjs/**/*.+(js|js.map)',
      '@angular/**/*.+(js|js.map)',
      'angular2-cookie/**/*.+(js|js.map)'
    ]
  });
};

Also add angular2-cookie to the map and packages object in the system-config.ts (path: ./src/system-config.ts)

/***********************************************************************************************
 * User Configuration.
 **********************************************************************************************/
/** Map relative paths to URLs. */
const map: any = {
  'angular2-cookie': 'vendor/angular2-cookie'
};

/** User packages configuration. */
const packages: any = {
  'angular2-cookie': {main: 'core.js', defaultExtension: 'js'},
};

Angular2 Webpack Starter

An Angular 2 Starter kit featuring Angular 2 and Webpack 2 by @AngularClass(Link: https://github.com/AngularClass/angular2-webpack-starter)

Add angular2-cookie to vendor.browser.ts (path: ./src/vendor.browser.ts)

// Angular 2
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/common';
import '@angular/forms';
import '@angular/http';
import '@angular/router';

// angular2 cookie
import 'angular2-cookie/core'

// AngularClass
import '@angularclass/hmr';

// RxJS
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

if ('production' === ENV) {
  // Production


} else {
  // Development

}

Add CookieService to the APP_PROVIDERS array in the app.module.ts file (path: ./src/app/app.module.ts):

// ...

// Application wide providers
const APP_PROVIDERS = [
  ...APP_RESOLVER_PROVIDERS,
  AppState,
  CookieService
];

// ...

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 {string} key Id to use for lookup.
 * @returns {string} Raw cookie value.
 */
get(key: string): string;

getObject()

Returns the deserialized value of given cookie key.

/**
 * @param {string} key Id to use for lookup.
 * @returns {Object} Deserialized cookie value.
 */
getObject(key: string): Object;

getAll()

Returns a key value object with all the cookies.

/**
 * @returns {Object} All cookies
 */
getAll(): any;

put()

Sets a value for given cookie key.

/**
 * @param {string} key Id for the `value`.
 * @param {string} value Raw value to be stored.
 * @param {CookieOptionsArgs} options (Optional) Options object.
 */
put(key: string, value: string, options?: CookieOptionsArgs): void;

putObject()

Serializes and sets a value for given cookie key.

/**
 * @param {string} key Id for the `value`.
 * @param {Object} value Value to be stored.
 * @param {CookieOptionsArgs} options (Optional) Options object.
 */
putObject(key: string, value: Object, options?: CookieOptionsArgs): void;

remove()

Remove given cookie.

/**
 * @param {string} key Id of the key-value pair to delete.
 * @param {CookieOptionsArgs} options (Optional) Options object.
 */
remove(key: string, options?: CookieOptionsArgs): void;

removeAll()

Remove all cookies.

/**
 */
removeAll(): void;

Options

Options object should be a type of CookieOptionsArgs 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.

Note

The build process and the file structure of this repository has respectively modeled after the awesome angular2-google-maps project of Sebastian Müller.

  • 参考:         angular2 services - angular 2 http withCredentials - Stack Overflow 结论:         1.可以在http请求时添加options         2.可以在拦截器统一对http请求进行封装 export class CustomHttpInterceptor implements HttpInterc

  • Angularjs前台存取cookie使用方式,支持html之间的调用 1.引入js文件 2.在moudel中加入[‘ngCookies’] ,具体是var app = angular.module(“logApp”,[‘ngCookies’]); 3.app.controller(“logCtrl”,function( c o o k i e S t o r e , cookieStore, c

  • 1、描述 本地存储是一个非常重要的功能,在angular中,我们使用ngCookies来解决存储问题。 2、ngCookie的简单示例 第一步、引入angular-cookies <script src="http://code.angularjs.org/1.2.9/angular.min.js"></script> <script src="http://code.angularjs.

  • 一、父组件给子组件传值@input 1、父组件调用子组件的时候传入数据 <app-header [msg]="msg"></app-header> 2、子组件引入Input模块 import { Component, OnInit,Input } from '@angular/core'; 3、子组件中@Input接收父组件传过来的数据 export class HeaderComponent i

  • angular-cookies.js <!DOCTYPE html> <html ng-app="myApp"> <head> <script src="https://cdn.jsdelivr.net/npm/angular@1.8.2/angular.js"></script> <script src="https://cdn.jsdelivr.net/npm/angular-cook

  • 最近的项目中用到angularjs,因为很多不熟悉,用起来有点困难。这不,今天就遇到了要设置cookiede 过期时间的问题。 通过查找资料,解决办法如下: 首先引入js文件,如下: <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> <script type="text/javascript" src=

  • Angular提供ngx-cookie-service来操作cookie 1、首先,安装ngx-cookie-service npm install ngx-cookie-service app.module.ts import { CookieService } from 'ngx-cookie-service'; @NgModule({ imports: [], providers

  • AngularJS中对cookie的操作封装了一个单独的模块,模块名为ngCookies,若想使用需在页面中先引入angular-cookies.js: <script src="js/angular.min.js"></script> <script src="js/angular-cookies.js"></script> 然后將ngCookies模块注入到我们自定义的模块的依赖模块中: va

  • 由于angular在调试时,是使用反向代理的方式访问后端,那么就可能出现cookie路径不同的状况,导致session无法正常起作用。 例如angular端请求的地址为http://localhost:4200/api/getName,反向代理到http://localhost:8080/backend/getName,由于端口号后的第一级路径不同,即"api"与“backend”不同,就出现了c

  • $cookiesProvider 使用$cookiesProvider改变$cookies服务的默认行为。 默认属性 path:字符串,cookies只在这个路径及其子路径可用。默认情况下,这个将会是出现在你基础标签上的网址路径。 domain:字符串,cookies只在这个域及其子域可用。为了安全问题,如果当前域不是需求域的或者其子域,那么用户代理不会接受cookies。 expires:字符串

  • angular简单示例—待办事项清单—事件,双向绑定,实现数据缓存 一、待办事项实现功能: 添加事项 显示待办事项和已完成事项及实现相应的功能 可以删除事项 二、具体实现代码实现步骤如下: 1、首先,进行Angular环境的搭建和项目创建 ctrl + c 结束服务 2、新建模块 终端输入: ng g component components/doList 3、编辑app.component.h

  • 登录密码错误: res.status=200;status_code=550,status_msg=‘密码错误’;=》首先进入then(success)里面,然后再判断是否ok。 404:403,401也是这个情况。 res.status=404,==》进入了catch里面。 // 401的时候,自动清除了cookie里的信息; 403的时候,并没有 其中:res.status即General里面

 相关资料
  • 问题内容: 我正在使用angular2和gulp开发一个节点应用程序。我编写了一个组件文件login.ts,如下所示: 我的bootstrap.ts文件是: 但是当我编译这些文件时,出现以下错误: 这是我的tsconfig.json: 我已经使用以下命令安装了angular2的类型: 请帮助纠正错误。 问题答案: @simon错误说的是输入错误。但是对于其他进口商品,我已经发布了此答案,可能对其他

  • Angular2 (Beta) -> Angular4 开发语言:ECMAScript6 的标准已经完成。浏览器可以支持模块、类、lambda 表达式、generator 等新特性。 开发模式:Web组件将很快实现。 移动化:针对移动优化,如:缓存预编译、触控支持。 ES6工具链 Angular2是面向未来的技术,浏览器需要支持ES6+,由于目前浏览器尚未实现ES6,需要使用垫片。 angular

  • jackblog-angular2 Jackblog 是使用 Node.js + MongoDB + 其它客户端框架开发的个人博客系统,前后端分离,仿简书模板. 服务端有: express 版 , koa 版 客户端有: angular1.x 版 , angular2.x 版 , react 版 , vue 版 移动端有: react native 版, ionic2.0 版 此为客户端angul

  • angular 2+ Spring Boot Integration This example shows how to do a paginated table with Angular and Spring Boot (RestController ) Installation The Back End You'll need Maven 3+ and Java 8 The Front End

  • Angular2 Tutorial This repository is an example application for angular2 tutorial. Demo Ahead-of-time compilation Lazy Loading Preloading CSS in JS by using Aphrodite Hot module reload Getting Started

  • Angular CRUD ops, Modals, Animations, Pagination, DateTimePicker, Directives and much more.. Read blog post Single Page Application built with Angular 4 and TypeScript Back-end API built with ASP.NET