如何摆脱 Angular 6 服务中的冗余请求?

编程入门 行业动态 更新时间:2024-10-24 14:18:15
本文介绍了如何摆脱 Angular 6 服务中的冗余请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-22 17:06:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1027038.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:冗余   Angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!