【发布时间】:2019-04-03 04:49:06
【问题描述】:
我正在接受 Web 开发正在发生变化的事实,我需要掌握 RxJS。我目前正在使用 Angular 2.0.0-beta.15 开发一个网络应用程序。
我在关注最优秀的ng-book 2(允许这种广告吗?哦,好吧)。它广泛而浅薄地涵盖了 RxJS 中的一些重要概念,并提供了进一步阅读的链接。我已经阅读并理解了源代码和随附的解释,但是对于有关 Subjects 的一些细节以及 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?我是否以错误的方式思考它?我需要彻底的心理重组/移植吗?
这么多问题!
【问题讨论】:
标签: angular typescript rxjs