【发布时间】:2021-10-12 09:20:00
【问题描述】:
前提条件
我有以下情况:
- 在后端我有一个端点,它提供数据。数据很少更改。
- 在前端我有几个组件,在加载后需要来自 p.1 的数据。
问题
如何避免对后端的多个请求(= 如何将第一个请求的结果共享给服务方法的所有其他调用)。
源代码-服务
@Injectable()
export class ConfigurationService {
private ConfigurationUrl: string = 'api/configurations/';
private httpHeaders: HttpHeaders;
// ...
constructor(private httpClient: HttpClient) {
}
// ...
loadCommonSettings(): Observable<CommonSettings> {
return this.httpClient.get<CommonSettings>(this.ConfigurationUrl + "common");
}
// ...
}
源代码 - 组件
export class HomeComponent {
constructor(public dialog: MatDialog, private configurationService: ConfigurationService, private _snackBar: MatSnackBar) {
}
isNewDisabled: boolean = true;
commonSettings: CommonSettings;
ngOnInit() {
this.loadCommonSettings();
}
//...
loadCommonSettings() {
this.configurationService.loadCommonSettings().subscribe(
res => {
this.isNewDisabled = false;
this.commonSettings = res;
},
err => {
this.openErrorDialog("Error", "Error on data loading");
}
);
}
//...
}
问题 每次调用 loadCommonSettings 服务函数都会向服务发起一个新请求。
假设
- 我想将数据存储在服务中,就像存储在缓存中一样,但无论如何我几乎同时调用了 2 个服务方法。
- 在这种情况下,Subjects 可能会有所帮助,但我完全不确定(因为看起来,Observables 也完全可以用于此类调用)。
【问题讨论】:
-
您熟悉服务人员吗?如果没有,请阅读:angular.io/guide/service-worker-intro
标签: angular rxjs request observable angular2-observables