美好的一天伙计, 我有这个疯狂的想法使用服务作为缓存存储。所以我在Service中定义了一些变量。数据更新完全正常,但不会反映在视图上。视图已经被填充,服务层随后运行。我不确定,即使将数据存储在服务中是一个好主意?请有人帮忙解释一下。 这里是我的服务代码:Angular 2 - 服务中定义的变量,不在视图中更新
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并订阅它的组件。我正在寻找另一种方式。不确定,如果它能做到? – leo