我接受了Web开发正在发生变化的事实,我需要掌握RxJS . 我目前正在使用Angular 2.0.0-beta.15开发一个Web应用程序 .
我追随最优秀的ng-book 2(这种广告是允许的吗?哦,好吧) . 它涵盖了RxJS中的一些重要概念,并提供了进一步阅读的链接 . 我已经阅读并理解了源代码和附带的解释,但我特别关注了有关 Subject
s的一些细节,以及Angular 2组件如何使用这些主题流 .
我这样增加了书中的代码:
export class SubmitResourceComponent {
private _newResourceTags: Subject<Tag> = new Subject<Tag>();
private _resourceTags: Observable<Tag[]>;
private _tagUpdates: Subject<any> = new Subject<any>();
private _create: Subject<Tag> = new Subject<Tag>();
private _remove: Subject<Tag> = new Subject<Tag>();
constructor() {
this._resourceTags = this._tagUpdates
.scan((tags: Tag[], operation: ITagsOperation) => operation(tags), initialTags);
this._create
.map((tag: Tag): ITagsOperation => (tags: Tag[]) => _.uniq(tags.concat(tag)))
.subscribe(this._tagUpdates);
this._remove
.map((tag: Tag): ITagsOperation => (tags: Tag[]) => _.without(tags, tag))
.subscribe(this._tagUpdates);
this._newResourceTags.subscribe(this._create);
}
get resourceTags(): Observable<Tag[]> {
return this._resourceTags;
}
protected addTagToResource(tag: Tag): void {
this._create.next(tag);
}
protected removeTagFromResource(tag: Tag): void {
this._remove.next(tag);
}
}
而我正在消耗这样的 _resourceTags
:
<button class="btn" *ngFor="#tag of resourceTags | async" (click)="removeTagFromResource(tag)">{{ tag.name }}</button>
即使在gitter论坛的出色支持下,我无法掌握的是UI显示所有被推入 _resourceTags
Subject
的标签的原因 . 我想象这个流就像一个橡皮管:一旦一个元素被推入 Subject
并发布到任何 Observer
(在这种情况下,UI元素),它是否会蒸发并消失?它会留在流/管道/ Subject
吗? UI元素如何订阅 Subject
?我是以错误的方式思考它的吗?我需要完整的心理重组/移植吗?
这么多的问题!
2 回答
传递给
next
的数据就像一个事件 . 订阅者获取值并且Subject
创建的Observable
不包含对它的任何引用(除非您使用特殊运算符来缓冲或通过其他方式保持发出的值 .使用
| async
Angular订阅Observable
(Subject
),当它收到一个值时,它会显示它 .*ngFor
仅渲染数组 . 如果要使用*ngFor
和Subject
,则主题需要发出数组 - 每个事件不是单个值,而是一个值数组,这些值由*ngFor
呈现,并在Observable
发出新数组时由其他值替换 .scan operator
您的代码示例使用
scan
运算符,其目的是累积发出的值并转发一个数组,该数组包含每次收到*ngFor
所需的新事件时到目前为止发出的所有值 .我认为observables只在会话被清除之前将变量的值存储在浏览器内存中,就像设置变量以从输入框中获取值一样,并且在浏览器上点击刷新后,值被清空 . 在上面的场景中,我会像大多数SPA一样认为浏览器无法进行刷新/重新加载的默认行为,并且你会得到某种持久性,所以当你进行类似的操作时
由于它们由create事件合并,值继续堆积,但是当页面上的手动刷新发生并清除会话时,这些值将消失
EDIT
也许我的问题是错的,但我的意思是:_resourceTags开始为空,一个值由create事件创建,现在 _resourceTags 是 [newValue#1] angular检测到更改并使用ngFor重新呈现_resourceTags,在新的创建事件后 _resourceTags 现在是 [newValue#1, newValue#2] angular rerenders现在显示 . 如果流没有被持久化到像firebase这样的在线数据库或者像websql这样的离线数据库,则意味着在重新加载浏览器时 _resourceTags 将返回为空