什么是ngCookies(AngularJS)在Angular 4或5

puruo6ea  于 2022-11-21  发布在  Angular
关注(0)|答案(3)|浏览(137)

Angular 4/5中AngularJS上的$cookie是多少?
例如在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');
}
vxf3dgd4

vxf3dgd41#

在Angular 4/5中有几个npm包可以用来处理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');
ghg1uchk

ghg1uchk2#

您可以使用**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 {}

1.然后,将其导入并注入组件:

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

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

cngwdvgl

cngwdvgl3#

您可以使用NGX Cookie Service

npm install ngx-cookie-service --save

yarn add ngx-cookie-service

将cookie服务作为提供程序添加到您的app.module.ts:

import { CookieService } from 'ngx-cookie-service';

@NgModule({
  ...
    providers: [CookieService],
  ...
})

export class AppModule {
}

然后,将其导入并注入构造函数:

constructor(
  private cookieService: CookieService
)
{
  this.cookieService.set('Test', 'Hello World');
  this.cookieValue = this.cookieService.get('Test');
}

就是这样!

相关问题