繁体   English   中英

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

[英]How to get rid from redundant request in Angular 6 service?

我的代码中有3个独立的位置,它们调用VerificationService方法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并不是重点

还有一个地方是组件:

export class VerificationComponent implements OnInit {
   constructor(private verificationService: VerificationService) {
   }

   ngOnInit() {
     this.verificationService.getOrganizationView()
       .subscribe((data: VerificationView) => {
         ...
     });
  }
}

在加载应用程序时,我只有3个调用,而不是单个请求,但是这些实体是绝对独立的,并且我不能像组件指令之间共享数据,等等。

在Angular 2+中,传统上如何解决这样的问题? 我的意思不是意思是不同的答案代码。

缓存数据的最简单方法是使用shareReplay rxjs运算符:

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$;
  }
}

也可以看看:

您可以构建一个检索和缓存数据的服务。 然后,注入服务的任何组件都可以访问该缓存的数据,而无需对服务器的另一个请求。

export class ProductService {
    private productsUrl = 'api/products';
    products: IProduct[];

    getProducts(): Observable<IProduct> {
        // Returns the cached list if it exists.
        if (this.products) {
            return of(this.products);
        }
        return this.http.get<IProduct[]>(this.productsUrl)
                        .pipe(
                            tap(data => this.products = data),
                            catchError(this.handleError)
                        );
    }
}

还有其他几个答案,包括在此处使用RxJS ReplaySubject在RxJs 5中共享Angular Http网络调用结果的正确方法是什么?

我不确定100%如何设置您的应用。 但是,如果我是您,我会考虑使用事件发射器 您可以让它发出一个事件,您的不同组件可以监听。 应该调用哪个组件都可以进行适当调用,而其他组件则不能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM