什么是Angular 4或5中的ngCookies(AngularJS)

时间:2018-03-23 09:59:08

标签: angularjs angular typescript cookies

Angular 4/5中AngularJS的$ cookies是什么?

例如在AngularJS

let app = angular.module('myApp', ['ngCookies']);
app.controller('MainController', MainController);
MainController.$inject = ['$scope', '$cookies'];
function MainController($scope, $cookies){
  $cookies.put('msg', 'Hello World');
  $scope.msgFromCookie= $cookies.get('msg');
}

2 个答案:

答案 0 :(得分:1)

有几个npm包可用于处理Angular4 / 5中的cookie。 例如  ngx-cookie-service,您可以使用npm

获取它
npm install ngx-cookie-service --save

您将cookie服务作为提供者添加到模块中(就像使用任何服务一样),然后将其注入组件并使用它。

import { CookieService } from 'ngx-cookie-service';
constructor(private cookieService: CookieService) { }

this.cookieService.set('msg', 'Hello World');
this.cookieService.get('msg');

答案 1 :(得分:0)

您可以使用 ngx-cookie-service

  1. 将cookie服务作为提供者添加到app.module.ts:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    
    import { AppComponent } from './app.component';
    import { CookieService } from 'ngx-cookie-service';
    
    @NgModule({
        declarations: [AppComponent],
        imports: [BrowserModule, FormsModule, HttpModule],
        providers: [CookieService],
        bootstrap: [AppComponent]
    })
    export class AppModule {}
    
  2. 然后,导入并将其注入组件:

     import { Component, OnInit } from '@angular/core';
     import { CookieService } from 'ngx-cookie-service';
    

    Referance:https://www.npmjs.com/package/ngx-cookie-service