美好的一天夥計, 我有這個瘋狂的想法使用服務作爲緩存存儲。所以我在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