问题
Based on this question here, I am using the Rxjs scan operator to keep track of all of the observables that get emitted in an the accumulator array, and then each new incoming value I am adding it to that internal accumulator array created by the scan operator and then I am emitting the single array. This allows me to bind to that array observable with the async pipe in the template and display previews of images user uploaded. However if I want to implement the remove or undo functionality, I have need access to that array to be able to remove an item from it.
This is my scan operator:
uploadPicture: Subject<UploadPicture> = new Subject<UploadPicture>();
previewPictures$ = this.uploadPicture.pipe(
scan(
(pictures, newPicture) => [...pictures, newPicture],
new Array<UploadPicture>()
)
);
Now when user clicks undo or remove on a picture, I want to take that value out of the array and update the view. Any ideas how this can be achieved?
`
回答1:
Emit the value once to add it, and emit it a second time to remove it. If you emit a third time it will be added back 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
This can be done easily in the template.
<div *ngFor="let pic of previewPictures$ | async">
<button (click)="uploadPicture.next(pic)">Remove</button>
</div>
来源:https://stackoverflow.com/questions/56309545/in-rxjs-scan-operator-is-it-possible-to-remove-an-item-from-the-internal-accumu