存在大部分组件中使用的主数据列表。
我曾经这样在ngInit中加载它。
ngOnInit() {
this.loadMasters();
}
loadMasters() {
this.masterService.getOrg().subscribe(response => {
if (response && response['result']) {
this.organisms = response['result'];
}
})
this.masterService.getCat().subscribe(response => {
if (response && response['result']) {
this.category = response['result'];
}
})
......................
}
此代码已在大多数组件中重复。
我需要标准解决方案
1)避免在所有组件中调用这些主服务器,因为这会导致不必要的服务器调用。为此,我首选解决方案。2)有什么办法可以缓存它。如果上面没有解决方案,请尝试此。
在masterService
中,您可以创建两个BehaviorSubject,例如:
categories$ = new BehaviorSubject<any>(null);
organizations$ = new BehaviorSubject<any>(null);
然后使用条件填充它们,以避免多次调用。将loadMasters移到服务内部,例如:
mastersService.ts
loadMasters() {
// check for value in org before doing request
if (!this.organizations$.value) {
this.masterService.getOrg().subscribe(response => {
if (response && response['result']) {
// set value into behavior subject
this.organizations$.next(response['result']);
}
})
}
// do the same for the categories
if (!this.categories$.value) {
this.masterService.getCat().subscribe(response => {
if (response && response['result']) {
// set value into behavior subject
this.categories$.next(response['result']);
}
})
}
...
}
然后在需要使用该值的所有位置,您都可以订阅行为主题,并在此之前调用loadMasters以确保已加载数据:
mycomponent.ts:
public ngOnInit(): void {
this.mastersService.loadMasters(); // load data if not loaded yet
// consume the data from the behavior subjects
this.mastersService.categories$.subscribe(value => {
console.log(value);
});
this.mastersService.organizations$.subscribe(value => {
console.log(value);
});
}