Using pure Observable vs array (from subscribe)

眉间皱痕 提交于 2019-12-06 07:11:15

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.

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