RxJS 主题和 Angular 2 组件

2024-02-18

我正在接受 Web 开发正在发生变化的事实,我需要掌握 RxJS。我目前正在使用 Angular 2.0.0-beta.15 开发一个网络应用程序。

我追随最优秀的NG书2 https://www.ng-book.com/2/(允许这种广告吗?哦,好吧)。它广泛而浅显地涵盖了 RxJS 中的一些重要概念,并提供了进一步阅读的链接。我已阅读并理解源代码和随附的解释,但对有关的一些细节一无所知Subject特别是 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?我是否以错误的方式思考这个问题?我需要彻底的精神重组/移植吗?

这么多的问题!


数据传递至next就像一个事件。订阅者获得值和Observable由创建的Subject不保留对它的任何引用(除非您使用特殊运算符来缓冲或通过其他方式保留发出的值。

With | asyncAngular 订阅了Observable (Subject),当它收到一个值时,它会显示它。

*ngFor只渲染数组。如果你想使用*ngFor with Subject,主题需要发出数组 - 每个事件不是单个值,而是一个值数组,并且这些值由以下方式呈现*ngFor并替换为其他值时Observable发出一个新数组。

扫描操作员 http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-scan

您的代码示例使用scan操作符的目的是累积发出的值,并在每次收到新事件时转发一个包含到目前为止发出的所有值的数组,如所需的*ngFor.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

RxJS 主题和 Angular 2 组件 的相关文章

随机推荐