问题描述
限时送ChatGPT账号..我的代码中有 3 个独立的地方,它们调用了 VerificationService
方法 getOrganizationView()
.
I have 3 independent places in my code which call VerificationService
method getOrganizationView()
.
getOrganizationView(): Observable<any> {
return this.httpClient.http.post(...)
}
第一名是主要服务:
@Injectable()
export class Principal {
constructor(private verificationService: VerificationService) {}
identity(force?: boolean): Promise<any> {
return this.verificationService.getOrganizationView().toPromise().then((response ) => {
...
})
}
}
还有一个名为 LinkAccessService
的服务,它执行相同的 Principal
这不是重点
And one more service called LinkAccessService
which do the same Principal
that's not the point
还有一个地方是组件:
export class VerificationComponent implements OnInit {
constructor(private verificationService: VerificationService) {
}
ngOnInit() {
this.verificationService.getOrganizationView()
.subscribe((data: VerificationView) => {
...
});
}
}
在加载应用程序时,我有 3 个调用而不是单个请求,但是这些实体绝对独立,我无法在组件指令之间共享数据等等...
And at loading app moment I had 3 calls instead single request, but these entities absolutely independent and I can't share data like between components directive and so on...
Angular 2+ 传统上如何解决这样的问题?我不是说答案的不同代码,我是说想法.
How traditionally in Angular 2+ resolve issue like this? I'm not mean distinct code for answer, I mean idea.
推荐答案
缓存数据的最简单方法是使用 shareReplay
rxjs 运算符:
The simplest way to cache your data is using shareReplay
rxjs operator:
import { shareReplay } from 'rxjs/operators';
@Injectable()
export class VerificationService {
organizationViewCache$: Observable<any>;
getOrganizationView() {
if (!thisanizationViewCache$) {
thisanizationViewCache$ = this.http.get(...).pipe(shareReplay(1));
}
return thisanizationViewCache$;
}
}
另见:
使用 RxJS 进行高级缓存这篇关于如何摆脱 Angular 6 服务中的冗余请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论