使用纯粹的Observable vs数组(从订阅) [英] Using pure Observable vs array (from subscribe)

查看:113
本文介绍了使用纯粹的Observable vs数组(从订阅)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



选项1 - 纯可观察

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

然后在HTML中使用异步管道(和rxjs运算符来处理数据)


$ b

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

然后处理作为一个正常的数组。

解决方案

正如olsn在注释中指出的那样,使用异步管道来处理但是,如果您选择使用手动订阅的方法出于任何原因(在向用户显示之前在客户端以某种方式操纵数据),那么您将ne编辑手动取消订阅。

基本上,你需要在你的组件中写这样的内容:

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

//然后在你的代码中的某处
ngOnDestroy(){
this.subscription.unsubscribe();



$ b $ p
$ b

为了避免手动取消订阅,以及只有需要的数据要读一次,你可以使用其中一个可用的运算符,如take()。

  this.angularFire。 (1).subscribe(response => this.schools = response)

这个方法将确保在第一次查询运行后observable被自动取消订阅。


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.

解决方案

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.

这篇关于使用纯粹的Observable vs数组(从订阅)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆