MST

星途 面试题库

面试题:Angular HTTP请求缓存策略下如何处理缓存过期与动态更新

在Angular应用中,已经使用缓存策略来缓存HTTP请求数据。现在要求实现缓存过期机制,例如缓存数据5分钟后过期,过期后再次请求应从服务器获取最新数据。同时,当服务器数据发生变化时(假设通过WebSocket接收到数据变化通知),要及时更新缓存。请描述实现思路并给出关键代码片段。
44.6万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 缓存结构设计:使用一个对象来存储缓存数据,每个缓存项包含数据本身、缓存时间戳。
  2. 缓存过期检查:在每次从缓存获取数据前,检查当前时间与缓存时间戳的差值是否超过设定的过期时间(如5分钟)。
  3. HTTP请求处理:在HTTP请求拦截器中处理缓存逻辑,优先从缓存获取数据,若缓存过期则发起新的HTTP请求并更新缓存。
  4. WebSocket数据更新:当通过WebSocket接收到数据变化通知时,找到对应的缓存项并更新数据及时间戳。

关键代码片段

  1. 缓存服务
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CacheService {
  private cache: { [key: string]: { data: any, timestamp: number } } = {};
  private expirationTime = 5 * 60 * 1000; // 5分钟

  get(key: string) {
    const cached = this.cache[key];
    if (cached && Date.now() - cached.timestamp < this.expirationTime) {
      return cached.data;
    }
    return null;
  }

  set(key: string, data: any) {
    this.cache[key] = { data, timestamp: Date.now() };
  }

  clear(key: string) {
    delete this.cache[key];
  }
}
  1. HTTP拦截器
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { CacheService } from './cache.service';
import { finalize } from 'rxjs/operators';

@Injectable()
export class CacheInterceptor implements HttpInterceptor {
  constructor(private cacheService: CacheService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const cached = this.cacheService.get(request.url);
    if (cached) {
      return new Observable(observer => {
        observer.next(cached);
        observer.complete();
      });
    }

    return next.handle(request).pipe(
      finalize(() => {
        next.handle(request).subscribe(response => {
          this.cacheService.set(request.url, response);
        });
      })
    );
  }
}
  1. WebSocket数据更新处理
import { Component, OnInit } from '@angular/core';
import { CacheService } from './cache.service';
import { WebSocketService } from './websocket.service'; // 假设的WebSocket服务

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

  ngOnInit() {
    this.webSocketService.dataChange.subscribe(({ url, newData }) => {
      this.cacheService.set(url, newData);
    });
  }
}

假设存在一个WebSocketService,其dataChange为一个Observable,当接收到数据变化通知时,发出包含请求URL和新数据的对象。在应用组件中订阅该Observable并更新缓存。同时,要在app.module.ts中注册CacheInterceptor

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform - browser';
import { AppComponent } from './app.component';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { CacheInterceptor } from './cache.interceptor';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CacheInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}