This article has not been translated, hope that your can PR to translated it. Help us!

Interceptor

写在前面

搭配 httpCacheInterceptor Http 拦截器,可以将缓存应用到 Http 请求当中。它只有几个特征:

  • 支持缓存过期时间

  • 支持自定义缓存 KEY

  • 支持任何 Http 请求、任何数据格式

  • 符合 Http 缓存响应标准 Cache-Control

如何使用

withInterceptors 中引入 httpCacheInterceptor

provideHttpClient(withInterceptors([httpCacheInterceptor]))

代码演示

value:

Basic:
Key is valid request:
Notify:
基础样例

最简单的用法。

expand code expand code
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-interceptor-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>
  `,
  standalone: true,
  imports: [JsonPipe, NzButtonModule]
})
export class CacheInterceptorSimpleComponent 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();
  }
}
Loading...