面试题答案
一键面试实现思路
- 使用
HttpClient
进行请求:利用Angular的HttpClient
模块发送HTTP请求获取用户信息、订单列表和收藏商品列表。 - 并发请求与合并结果:使用RxJS的
forkJoin
操作符并发执行多个请求,并将它们的结果合并成一个数组。 - 缓存策略:创建一个缓存对象,在每次请求前检查缓存中是否已有数据。如果有,直接从缓存中获取;否则,发起网络请求,并在请求成功后将结果存入缓存。
关键代码
假设使用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;
});
}
}