简体   繁体   English

如何在 Angular 2 的多个组件中使用 rxjs Observables

[英]How to use rxjs Observables in multiple Components in Angular 2

For a mindmap-like learning app all elements (lines/text) are placed via different Components in the view.对于类似思维导图的学习应用程序,所有元素(行/文本)都通过视图中的不同组件放置。 The data is fetched from a database and saved in an ObservableArray if it's in the view.如果数据在视图中,则从数据库中获取数据并保存在 ObservableArray 中。 There are two distinct kind of changes: 1. scrolling, the view changes and new data is fetched;有两种截然不同的变化: 1. 滚动,视图发生变化并获取新数据; 2. the user changes/adds/deletes an element in the view (no new data is fetched). 2. 用户更改/添加/删除视图中的元素(不获取新数据)。

Is it better to "read" the observable to an ObjectArray iterate it with *ngFor, passing each Object to the matching Component or only pass an array of ids and letting each Component subscribe to the matching Element inside the ObservableArray?将可观察对象“读取”到 ObjectArray 是否更好,使用 *ngFor 对其进行迭代,将每个对象传递给匹配的组件,或者只传递一个 id 数组并让每个组件订阅 ObservableArray 中的匹配元素?

So far I am using the first approach that I've seen in many tutorials and examples but using the second would make the user changes much easier and only the relevant elements would be change detected.到目前为止,我正在使用我在许多教程和示例中看到的第一种方法,但使用第二种方法会使用户更改更容易,并且只会检测到相关元素的更改。

I think first way is still better.我认为第一种方式仍然更好。 On optimization side you can use trackBy feature of *ngFor在优化方面,您可以使用*ngFor trackBy功能

<div *ngFor="let item for (items | async); trackBy: item?id">
  <item [item]="item"></item>
</div>

This assumes your item has an unique id.这假设您的项目具有唯一 ID。 This will ensure each item element will not be rendered again.这将确保不会再次呈现每个item元素。 Additionally set changeDetectionStrategy of the item component as OnPush .另外将 item 组件的changeDetectionStrategy设置为OnPush So, the item components change detection will be fired only when the input , ie item changes.因此,仅当输入(即item更改时才会触发项目组件更改检测。

Basically item component should be dumb (presentational) component, which only displayed the item data.基本上item组件应该是哑(展示)组件,它只显示项目数据。

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

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