如何摆脱 Angular 6 服务中的冗余请求? [英] How to get rid from redundant request in Angular 6 service?

查看:20
本文介绍了如何摆脱 Angular 6 服务中的冗余请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有 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 (!this.organizationViewCache$) {
      this.organizationViewCache$ = this.http.get(...).pipe(shareReplay(1));
    }

    return this.organizationViewCache$;
  }
}

另见:

这篇关于如何摆脱 Angular 6 服务中的冗余请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆