Using pure Observable vs array (from subscribe)

2019-05-21 04:13发布

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条回答
时光不老,我们不散
2楼-- · 2019-05-21 05:00

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.

查看更多
登录 后发表回答