每天学习一点点,成功增加一大步

Angular笔记:Cookies 使用

Angular zhanghui 2361℃

昨天的做小项目实践的时候,在做登陆的最后一步的信息存储时遇到 angular5(这是当时 angular-cil 的版本) 如何使用 cookies 作为前端的存储容量。在 angular 的手册找来找去却未能找到有关的信息。只是在搜索引擎上找到了个 angular2-cookies 找到当初我还以为这个依赖库只能用于 angular2,没有想到它也能用于 angular2 以上的版本。后来也是因为找来找去实在没有其他办法,最后只好拿来试试,最后还真是成功了。

现在记录下使用的过程。

1、在项目中安装 angular2-cookies 依赖库

npm install angular2-cookie --save

网络上说在完成这步之后,还要进行“After installing the library, it should be included in the SystemJS configurations.”,但后来发现在使用 angular-cli 的时候无须这步的操作。

2、在项目的 AppModule 中注入 cookiesService 服务

@NgModule({
  declarations: [
    AppComponent,
    UserLoginComponent,
    AdminComponent,
    Code404Component,
    AlertComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpModule,
    ReactiveFormsModule
  ],
  providers: [HttpService, CookieService],
  bootstrap: [AppComponent]
})

完成以上两步操作后就可以在需要使用 cookies 的 component 中引入使用了。

import {Component, OnInit} from '@angular/core';
import {Router} from "@angular/router";
import {CookieService} from 'angular2-cookie/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

  private _token: string;

  constructor(private router: Router,
              private cookieServ: CookieService) {
    this._token = cookieServ.get('token');
  }

  ……

}

而 cookies 服务里面的都有哪些方法呢?

get(key: string): string

通过一个String类型的key获取一个String类型的数据。

getObject(key: string): Object

通过一个String类型的key获取一个Object类型的数据。

getAll(): any

获取所有Cookie中保存的内容。

put(key: string, value: string, options?: CookieOptionsArgs): void

保存string类型的数据。

putObject(key: string, value: Object, options?: CookieOptionsArgs): void

保存Object类型的数据。

remove(key: string, options?: CookieOptionsArgs): void

删除指定的数据。

removeAll(): void

删除所有数据。

CookieOptionsArgs(cookies 的其他选项参数):

  • path – [string] – 保存路径,保存的数据只适用于输入路径及其子路径,路径是基于<base>标签中的路径。
  • domain – [string] – 保存域,保存的数据只适用于当前域及其子域,
  • expires – [string|Data] – “Wdy, DD Mon YYYY HH:MM:SS GMT”样式的字符串或者Data类型,设置保存数据的到期日期。
  • secure – [boolean] – 如果设置为true,数据只能通过安全连接获取。

转载请注明:隨習筆記 » Angular笔记:Cookies 使用

喜欢 (0)