writes at beginning, sometime we need to save data into localStorage and control its life ourselves , and here is a good open source tool helps do this

 

1. for example , get a user form localStorage

1  constructor(private localStorageService: LocalStorageService, public  client: HttpClient) {
2 
3   }
4 
5   getUserFromLocalStorage(): Observable<User | null> {
6     const temp = this.localStorageService.get(User.identifier);
7     return temp ? of(temp) : of(null);
8   }

all you need to attention is the   .get(User.identifier)  method ,  it looks for data in localStorage with given identifier , in this case the valuei is user$ ,  it matters nothing, or you can check the whole definition below

 1 export class User {
 2   static identifier = 'user$';
 3   username: string;
 4   token: Token;
 5   id: number;
 6 
 7   constructor(username: string, token: Token, id: number) {
 8     this.username = username;
 9     this.token = token;
10     this.id = id;
11   }
12 }
13 
14 
15 
16 export class Token {
17   public static identifier = 'token$';
18   sysUserId: number;
19   username: string;
20   accessToken: string;
21 
22   constructor(sysUserId: number, username: string, accessToken: string) {
23     this.sysUserId = sysUserId;
24     this.username = username;
25     this.accessToken = accessToken;
26   }
27 }
user.ts

 

2. and save a user to localStorage

 

saveUserToLocalStorage(token?: Token, user?: User) {
    if (token) {
      this.localStorageService.set(User.identifier, new User(token.username, token, token.sysUserId));
      return;
    }
    this.localStorageService.set(User.identifier, user);
  }

 

3. or control with the ttl

 1 import {ExpiredUnit} from 'angular-web-storage/src/util';
 2 
 3 export class Address {
 4   static identifier= 'address$';
 5   static expiredAt = 1;
 6   static expiredUnit: ExpiredUnit = 'h';
 7 
 8   ret: number;
 9   data: Data;
10   msg: string;
11 }
12 ....
13 saveAddress(address: Address): void {
14     this.localStorageService.set(Address.identifier, address, Address.expiredAt, Address.expiredUnit);
15   }

 

 

 

posted on 2019-06-17 15:00  四维胖次  阅读(446)  评论(0编辑  收藏  举报