MST

星途 面试题库

面试题:Angular HttpClient模块与RxJS结合优化并发请求及缓存策略

假设有多个后端接口,分别获取用户信息、用户订单列表、用户收藏商品列表。这些接口都需要使用HttpClient模块进行请求。要求使用RxJS操作符优化这些并发请求,例如合并请求结果,并且实现一个简单的缓存策略,当再次请求相同数据时,优先从缓存中获取而不是再次发起网络请求。请详细说明实现思路并给出关键代码。
18.5万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 使用HttpClient进行请求:利用Angular的HttpClient模块发送HTTP请求获取用户信息、订单列表和收藏商品列表。
  2. 并发请求与合并结果:使用RxJS的forkJoin操作符并发执行多个请求,并将它们的结果合并成一个数组。
  3. 缓存策略:创建一个缓存对象,在每次请求前检查缓存中是否已有数据。如果有,直接从缓存中获取;否则,发起网络请求,并在请求成功后将结果存入缓存。

关键代码

假设使用Angular框架:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, forkJoin, from } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class UserDataService {
  private userInfoCache: any;
  private orderListCache: any;
  private favoriteListCache: any;

  constructor(private http: HttpClient) {}

  getUserData(): Observable<{ userInfo: any, orderList: any, favoriteList: any }> {
    const userInfo$ = this.getCachedOrFetch('userInfo', () => this.http.get('/api/userInfo'));
    const orderList$ = this.getCachedOrFetch('orderList', () => this.http.get('/api/orderList'));
    const favoriteList$ = this.getCachedOrFetch('favoriteList', () => this.http.get('/api/favoriteList'));

    return forkJoin({
      userInfo: userInfo$,
      orderList: orderList$,
      favoriteList: favoriteList$
    });
  }

  private getCachedOrFetch(cacheKey: string, fetchFn: () => Observable<any>): Observable<any> {
    const cache = this[cacheKey + 'Cache'];
    if (cache) {
      return from([cache]);
    } else {
      return fetchFn().pipe(
        shareReplay(1),
        map(data => {
          this[cacheKey + 'Cache'] = data;
          return data;
        })
      );
    }
  }
}

在组件中使用:

import { Component } from '@angular/core';
import { UserDataService } from './user-data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  userData: { userInfo: any, orderList: any, favoriteList: any };

  constructor(private userDataService: UserDataService) {
    this.userDataService.getUserData().subscribe(data => {
      this.userData = data;
    });
  }
}