使用纯 Observable 与数组(来自订阅) [英] Using pure Observable vs array (from subscribe)

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

问题描述

我想知道关于使用纯 observable 与订阅 observable 并使用数组的最佳实践.

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

选项 1 - 纯可观察"

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

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

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

选项 2 - 订阅数组"

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

然后把它当作一个普通的数组.

and then treat it as a normal array.

推荐答案

正如 olsn 在评论中指出的那样,使用异步管道来处理这种情况总是更实用.

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();
}

为了避免必须手动取消订阅,如果数据只需要读取一次,您可以使用一种可用的运算符,例如 take().

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)

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

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

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

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