我的代码中有三个独立的地方,它们称为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个调用,而不是一个请求,但是这些实体是完全独立的,我不能在组件指令等之间共享数据。
传统的角度2+是如何解决这样的问题的?我不是指不同的答案,我指的是想法。
发布于 2018-12-11 11:27:36
缓存数据的最简单方法是使用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$;
}
}
另请参阅:
发布于 2018-12-11 09:36:05
您可以构建一个检索和缓存数据的服务。然后,任何注入该服务的组件都可以访问缓存的数据,而无需向服务器发出其他请求。
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中共享角Http网络调用结果的正确方法是什么?
发布于 2018-12-11 09:35:51
我不能百分之百确定你的应用程序是如何设置的。但是如果我是你的话,我会考虑使用事件发射器。您可以让它发出一个事件,您的不同组件将监听该事件。应该调用的任何组件都会适当地进行调用,而其他组件则不应该这样做。
https://stackoverflow.com/questions/53729362
复制相似问题