大家好,我有一个疯狂的想法,将服务用作缓存存储。所以我在 Service 中定义了几个变量。数据在服务中可以正常更新,但更改未反映在视图中。视图已填充,然后运行服务层。我不确定,即使在服务中存储数据是个好主意?有人可以解释一下吗?这是我的服务代码:
categories : SelectItem[]=[];
constructor(private utilityService:UtilityService) {
}
//populate all drop downs array with initial data from db
populateAll() {
//get categories
this.getCategories();
//there are lot more calls here
}
private getCategories() {
if(this.categories.length==0){
this.utilityService.getAllCategories().subscribe(cat=>{
this.categories =
this.utilityService.getSelectItemPublished(cat,"Category");
})
}
}
这就是我在组件中调用它的方式
constructor(
private cache:CacheStoreService,
) { }
ngAfterViewInit()
{
this.categories=this.cache.categories;
this.depts=this.cache.depts;
this.focuses=this.cache.depts;
this.statuses=this.cache.statuses;
this.phases=this.cache.statuses;
this.visibilities=this.cache.visibilities;
}
ngOnInit() {
this.cache.populateAll();
感谢您的帮助。还有一个问题:如何在 db-update 缓存中添加新数据时更新服务变量。**我知道,我可以返回 observable 并在组件中订阅它。我正在寻找另一种方式。不确定,如果它能够做到吗?**
谢谢
这是发生的事情:
this.cache.populateAll()
有几种方法可以解决这个问题。
第一种方法是避免用另一个数组替换数组,而是填充原始数组。
第二种方法是始终从服务请求数组,而不是在组件中存储第二个引用:
get categories() {
return this.cache.categories;
}
第三种方法是从服务中的 observable 发出一个事件,组件将订阅该事件以获取新类别。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句