gpt4 book ai didi

angular - 在 Rxjs 扫描运算符中,是否可以从扫描运算符创建的内部累加器中删除项目?

转载 作者:行者123 更新时间:2023-12-02 03:15:26 25 4
gpt4 key购买 nike

基于这个问题here ,我使用 Rxjs 扫描运算符来跟踪累加器数组中发出的所有可观察量,然后将每个新的传入值添加到扫描运算符创建的内部累加器数组中,然后发出单个数组。这允许我使用模板中的异步管道绑定(bind)到可观察的数组,并显示用户上传的图像的预览。但是,如果我想实现删除或撤消功能,我需要访问该数组才能从中删除项目。

这是我的扫描运算符(operator):

uploadPicture: Subject<UploadPicture> = new Subject<UploadPicture>();
previewPictures$ = this.uploadPicture.pipe(
scan(
(pictures, newPicture) => [...pictures, newPicture],
new Array<UploadPicture>()
)
);

现在,当用户单击图片上的“撤消”或“删除”时,我想从数组中取出该值并更新 View 。有什么想法可以实现这一点吗?

`

最佳答案

发出一次值以添加它,然后发出第二次以将其删除。如果您第三次发出,它将再次添加回来。

const uploadPicture = new Subject<UploadPicture>();

this.previewPictures$ = uploadPicture.pipe(
scan<<UploadPicture, UploadPicture[]>(
(pictures, newPicture) => pictures.includes(newPicture) ? pictures.filter(p=>p !== newPicture) : [...pictures, newPicture],
[]
)
);

const pic = new UploadPicture();
this.uploadPicture.next(pic); // this will add the picture
this.uploadPicture.next(pic); // this will remove the picture

这可以在模板中轻松完成。

<div *ngFor="let pic of previewPictures$ | async">
<button (click)="uploadPicture.next(pic)">Remove</button>
</div>

关于angular - 在 Rxjs 扫描运算符中,是否可以从扫描运算符创建的内部累加器中删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56309545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com