简体   繁体   English

角度4-可观察/阵列或可观察/主题

[英]Angular 4 - Observable/Array or Observable/Subject

In my project, we are manipulating and store data in services with array and Observables. 在我的项目中,我们正在使用数组和Observables在服务中处理和存储数据。 We create the observables like this : 我们创建这样的可观察对象:

Observable.of(array) Observable.of(数组)

and then we only update the array when we add/remove/etc element. 然后仅在添加/删除/ etc元素时更新数组。

In our component, we only consume the observable and use the async filter. 在我们的组件中,我们仅消耗可观察对象并使用异步过滤器。

I was wondering if it's good practice because even in the documentation of Angular, they recommend to use combination of Observable and Subject, not Observable and Array. 我想知道这是否是一个好习惯,因为即使在Angular的文档中,他们也建议结合使用Observable和Subject,而不是Observable和Array。

Why using Subject is better ? 为什么使用Subject更好? Is there a difference in the performance ? 性能上有区别吗?

Thanks 谢谢

Observable and Subject are different. 可观察和主题不同。 I don't see a benefit in casting your arrays to observables just so that you can use the async pipe because it will work just fine if you use the array directly in the template without async pipe and without casting it to an observable. 我看不到将数组强制转换为可观察对象的好处,因为您可以使用异步管道,因为如果您直接在模板中使用数组而不使用异步管道并且不将其强制转换为可观察对象,那么它将很好地工作。

A subject by definition is both an observable and an observer, meaning that you can both read and write values to it. 根据定义,主题既是可观察对象,也是观察者,这意味着您可以对其进行读取和写入值。 An observable you will only be able to read values from. 可观察的您将只能从中读取值。 What you are doing with Observable.of() is that you're creating a new observable each time. 使用Observable.of()所做的是每次都创建一个新的Observable。

With a subject, you can pass it/emit new values by using mySubject.next('new value') and you can then subscribe to the values just like you would an observable with mySubject.subscribe(). 对于主题,您可以使用mySubject.next('new value')传递/发出新值,然后可以订阅这些值,就像使用mySubject.subscribe()进行观察一样。

So one is not better than the other, they are just for different purposes. 因此,一个没有比另一个更好,它们只是出于不同的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM