ser*_*gpa 5 rxjs typescript angular
我接受了Web开发正在发生变化的事实,我需要掌握RxJS.我目前正在使用Angular 2.0.0-beta.15开发一个Web应用程序.
我正在关注最优秀的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);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在消费_resourceTags这样的:
<button class="btn" *ngFor="#tag of resourceTags | async" (click)="removeTagFromResource(tag)">{{ tag.name }}</button>
Run Code Online (Sandbox Code Playgroud)
即使在gitter论坛的出色支持下,我无法掌握的是UI显示所有被推入的标签的原因_resourceTags Subject.我想象这个流就像一个橡皮管:一旦一个元素被推入Subject并发布到任何东西Observer(在这种情况下,UI元素),它是否会蒸发并消失?它留在流/管道/ Subject?UI元素如何订阅Subject?我是以错误的方式思考它的吗?我需要完整的心理重组/移植吗?
这么多的问题!
传递给的数据next就像一个事件.订户获取值并且Observable由其创建的值Subject不包含任何引用(除非您使用特殊运算符来缓冲或通过其他方式保持发出的值.
使用| asyncAngular订阅Observable(Subject),当它收到一个值时,它会显示它.
*ngFor只渲染数组.如果你想使用*ngFor与Subject,受试者需要发射阵列-每个事件是不是一个单一的值,但值的阵列,并且这些值被绘制*ngFor并替换为其他值时,Observable发出一个新的数组.
您的代码示例使用scan运算符来累积发出的值并转发一个数组,该数组包含每次收到所需的新事件时到目前为止发出的所有值*ngFor.
| 归档时间: |
|
| 查看次数: |
6874 次 |
| 最近记录: |