我的代码中有 3 个独立的地方调用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
这不是重点
还有一处是组件:
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$;
}
}
也可以看看:
- 使用 RxJS 进行高级缓存 https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)