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

查看:57
本文介绍了如何摆脱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天全站免登陆