【问题标题】:Angular 2 - Variable defined in Service, not updating in viewAngular 2 - 在服务中定义的变量,不在视图中更新
【发布时间】:2017-09-11 15:30:52
【问题描述】:

大家好, 我有一个疯狂的想法,将服务用作缓存存储。所以我在服务中定义了一些变量。数据在服务中可以正常更新,但更改不会反映在视图上。视图已经被填充并且服务层随后运行。我不确定,即使在服务中存储数据是个好主意?请有人解释一下。 这是我的服务代码:

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 并在组件中订阅它。我正在寻找另一种方式。不确定,如果可以吗? **

谢谢

【问题讨论】:

  • 很难用给定的代码来判断,但是在组件的订阅块中,您的下一个回调看起来像是在调用另一个函数。你在那里正确地打盹你的结果吗?如果该函数返回另一个 observable,您可以在模板中使用异步管道。至于您的第二个问题,我相信您需要某种实时数据库解决方案。
  • 我知道,我可以让返回 observable 并在组件中订阅它。我正在寻找另一种方式。不确定,如果可以吗?

标签: angular


【解决方案1】:

会发生什么:

  1. 服务已初始化,其类别为空数组
  2. 您通过调用this.cache.populateAll() 告诉服务获取数据
  3. 服务方法发送异步请求
  4. 组件在其自己的类别中存储对服务类别数组的引用。数组还是空的
  5. 很久之后,异步请求的响应回来了。回调被调用。它不会填充服务和组件引用的数组。相反,它将一个新数组分配给服务的类别字段。该组件仍然引用旧的空数组。

有几种方法可以解决这个问题。

第一种方法是避免将数组替换为另一个数组,而是填充原始数组。

第二种方法是始终从服务请求数组,而不是在组件中存储第二个引用:

get categories() {
  return this.cache.categories;
}

第三种方法是从服务中的 observable 发出事件,组件将订阅该事件以获取新类别。

【讨论】:

  • 非常感谢@JB Nizet。感激。现在请您回答其他问题。如何用新数据填充/推送服务数组。假设来自 addCategory 组件的新类别。
  • 好吧,给你的服务添加一个 addCategory(category) 方法,this.categories.push(category)?
  • 但类别是从其他服务(即 CategoryService)添加的。我想发送一个对象到缓存服务...
猜你喜欢
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
  • 2020-11-27
  • 2019-05-11
  • 1970-01-01
  • 2017-04-07
相关资源
最近更新 更多