gpt4 book ai didi

angular - RXJS Angular一次调用一个方法并存储结果,在所有后续请求中返回存储的数据

转载 作者:行者123 更新时间:2023-12-02 04:20:40 26 4
gpt4 key购买 nike

从查询表中获取数据!

如果已经获取,则从localStorage获取数据或按服务获取,然后存储到localStorage中。

如果先前的请求已在处理中,则其他请求应等待完成,以便它们可以从localStorage获取数据

伪代码:

isInProgress = false;
getLookup(lookupName: string) {
if(this.isInProgress)
// Code to wait, no delay or timer, please


if(localStorage(lookupName)){
return of(localStorage.get(lookupName));
} else {
this.isInProgress = true;
let url = `..../getLooup?name= {lookupName}`;
this.httpClient.get(url).subscribe(data => {
// Some other code to process the logic
let processedData = someProcess(data);
localStorage.set(lookupName, processedData);
this.isInProgress = false;
return of(processedData)
}, error => {
this.isInProgress = false;
// Log error and other code
})
}
}

我的RXJS不太好,可能是一个简单的解决方案!

如果将这样调用:
xvyService.getLookup('A').subscribe(.....);
xvyService.getLookup('A').subscribe(.....);
xvyService.getLookup('A').subscribe(.....);
xvyService.getLookup('A').subscribe(.....);

数据库命中不应超过一次。

最佳答案

shareReplay可用于实现简单的缓存。它在第一个订阅上订阅一次源Observable,然后将值重播到所有以后的订阅。如果无法立即重播任何值,以后的订阅将自动“等待”。

一般逻辑

if value in local storage
return from local storage
else if cache not initialized
cache = apiCall.pipe(
// do things on first call only
shareReplay(1) // replay last value
// do things on all calls
)
endif
return cache

演示: https://stackblitz.com/edit/angular-cwbtyc?embed=1&file=src/app/app.component.ts

let cache$: Observable<any>;

getLookup(lookupName: string): Observable<any> {
const fromStorage = localStorage.getItem("lookupName");
if (fromStorage) {
console.log("from local storage");
return of(JSON.parse(fromStorage));
} else if (!this.cache$) {
console.log("initializing cache");
this.cache$ = this.requestData().pipe(
map(data => {
console.log('doing stuff');
const processedData = { ...data, a: 1 }
localStorage.setItem("lookupName", JSON.stringify(processedData));
return processedData
}),
shareReplay(1),
// Move catchError above shareReplay if you want to replay the safe error value instead
catchError(error => {
// Log error and other code - return default value on error
return of(null);
})
// Populate local storage on every call and not just the first one
//tap(data => localStorage.setItem("lookupName", JSON.stringify(data)))
);
}
return this.cache$;
}

关于angular - RXJS Angular一次调用一个方法并存储结果,在所有后续请求中返回存储的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60078460/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com