- 文档
- 开始使用
- CacheService
- Interceptor
value:
import { JsonPipe } from '@angular/common';
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { CacheService } from '@delon/cache';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzMessageService } from 'ng-zorro-antd/message';
@Component({
selector: 'cache-service-simple',
template: `
<p>value: {{ value | json }}</p>
<div class="pt-sm">
Basic:
<button nz-button (click)="srv.set(key, newValue)">Set</button>
<button nz-button (click)="value = srv.getNone(key)">Get</button>
<button nz-button (click)="srv.remove(key)">Remove</button>
<button nz-button (click)="srv.clear()">Clear</button>
</div>
<div class="pt-sm">
Key is valid request:
<button nz-button (click)="getByHttp()">Get</button>
</div>
<div class="pt-sm">
Notify:
<button nz-button (click)="registerNotify()">Register</button>
<button nz-button (click)="unRegisterNotify()">UnRegister</button>
</div>
`,
imports: [JsonPipe, NzButtonModule]
})
export class CacheServiceSimple implements OnDestroy {
value: any;
key = 'demo';
private notify$?: Subscription;
get newValue(): number {
return +new Date();
}
constructor(
public srv: CacheService,
private msg: NzMessageService
) {}
getByHttp(): void {
this.srv.get(`https://randomuser.me/api/?results=1`).subscribe(res => {
this.value = res;
});
}
registerNotify(): void {
if (this.notify$) this.notify$.unsubscribe();
this.notify$ = this.srv.notify(this.key).subscribe(res => {
if (res == null) {
this.msg.success('register success');
return;
}
this.msg.warning(`"${this.key}" new status: ${res.type}`);
});
}
unRegisterNotify(): void {
this.srv.cancelNotify(this.key);
}
ngOnDestroy(): void {
if (this.notify$) this.notify$.unsubscribe();
}
}| 参数名 | 类型 | 描述 |
|---|---|---|
key | string | 缓存唯一标识符 |
data | `any | Observable |
options | `{ type?: 'm' | 's', expire?: number, emitNotify?: boolean }` |
| 参数名 | 类型 | 描述 |
|---|---|---|
key | string | 缓存唯一标识符 |
options | `{ mode?: 'promise' | 'none', type?: 'm' |
获取缓存数据,若 key 不存在或已过期则返回 null。
获取缓存,若不存在则设置缓存对象,参数等同 set()。
是否缓存 key。
移除缓存 key。
清空所有缓存。
key 监听,当 key 变更、过期、移除时通知,注意以下若干细节:
cancelNotify 否则永远不过期freq (默认:3秒) 执行一次过期检查取消 key 监听
key 是否已经监听
清空所有 key 的监听
设置监听频率,单位:毫秒且最低 20ms,默认:3000ms。
get 和 tryGet 的区别本质都是获取并返回缓存数据,get 相比 tryGet 更简化,前者按KEY即是URL约定的风格,后者需指定数据源对象。
RxJS 和 async 管道二者的配合可以帮助我们非常友好的使用缓存数据,例如:
@Component({
template: `
@for (unit of units | async; track $index) {
<li>{{unit}}</li>
}`
})
export class Component {
units: this.srv.get('/data/unit')
}
有时需要依赖字典获取远程数据时:
this.srv
.get('/data/unit')
.pipe(
map(units => this.http.get(`/trade?unit=${units}`))
);