基于这个问题here,我正在使用Rxjs扫描运算符来跟踪在累加器数组中发出的所有可观察值,然后将每个新的传入值添加到内部由扫描运算符创建的累加器数组,然后发出单个数组。这使我可以绑定到可通过模板中的异步管道观察到的数组,并显示用户上传的图像的预览。但是,如果要实现删除或撤消功能,则需要访问该数组才能删除其中的项目。
这是我的扫描操作员:
uploadPicture: Subject<UploadPicture> = new Subject<UploadPicture>();
previewPictures$ = this.uploadPicture.pipe(
scan(
(pictures, newPicture) => [...pictures, newPicture],
new Array<UploadPicture>()
)
);
现在,当用户单击撤消或删除图片时,我想从数组中取出该值并更新视图。有什么想法可以实现吗?
`
答案 0 :(得分:3)
发出一次值将其添加,然后再次发出一次以将其删除。如果您第三次发射,它将被重新加回agan。
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>