Using pure Observable vs array (from subscribe)

雨燕双飞 提交于 2019-12-22 12:59:32

问题


I was wondering about best practices regard using pure observable vs subscribe to an observable and use an array.

option 1 - "pure observable"

this.schools = this.angularFire.database.list('schools') 

and then in the HTML use async pipe (and rxjs operators for handling the data)

option 2 - "subscribe to array"

this.angularFire.database.list('schools').subscribe (response => this.schools=response) 

and then treat it as a normal array.


回答1:


As olsn pointed out in the comments, it is always more practical to use the async pipe to handle this situation.

However, if you choose to use the manual subscribe approach for whatever reason (manipulating the data somehow on the client side before showing it to the user), you will need to manually unsubscribe as well.

Basically, you would need to write something like this inside your component:

ngOnInit(){
this.subscription = this.angularFire.database.list('schools').subscribe(response => this.schools=response) 
}

//then somewhere in your code
ngOnDestroy(){
   this.subscription.unsubscribe();
}

In order to avoid having to unsubscribe manually and if it is data that only needs to be read once, you could use one of the operators available to you like take() for example.

this.angularFire.database.list('schools').take(1).subscribe(response => this.schools=response)

This approach will make sure the observable is unsubscribed to automatically after the query runs the first time.



来源:https://stackoverflow.com/questions/41446899/using-pure-observable-vs-array-from-subscribe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!