- 原理阐述:
shareReplay
操作符可以将源Observable发出的值进行缓存,并在新的订阅者订阅时,重新播放这些缓存的值。它有两个参数,第一个参数bufferSize
表示缓存值的数量,第二个参数windowTime
表示缓存的时间窗口(以毫秒为单位)。在获取用户信息这种场景下,我们可以设置bufferSize
为1(因为只需要缓存最新的用户信息),并根据实际需求设置windowTime
,比如10000毫秒(10秒),在这10秒内多次请求用户信息,就可以从缓存中获取数据,而不需要再次向服务器请求。
- 代码示例:
- 首先,假设我们有一个服务用于获取用户信息,例如
UserService
:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { shareReplay } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UserService {
private userInfo$: Observable<any>;
constructor(private http: HttpClient) {}
getUserInfo(): Observable<any> {
if (!this.userInfo$) {
this.userInfo$ = this.http.get('/api/userInfo')
.pipe(
shareReplay(1, 10000) // 缓存最新的1个值,缓存时间为10秒
);
}
return this.userInfo$;
}
}
import { Component } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
userInfo: any;
constructor(private userService: UserService) {
this.userService.getUserInfo().subscribe(info => {
this.userInfo = info;
});
// 假设在10秒内再次请求
setTimeout(() => {
this.userService.getUserInfo().subscribe(info => {
// 这次请求会从缓存中获取数据
this.userInfo = info;
});
}, 5000);
}
}