嗯,一切都很好,但并不像我预期的那样。当用户保存图像时,我尝试从组件A获取当前值,并通过服务(使用BehaviorSubject )共享该img并将其存储在组件B中。我知道我总是获得当前值,但我的意图是存储最后一个值并保存我想要的所有图像,而不仅仅是用最后一个值覆盖当前值。
当前问题:我总是只存储最后一张图片。我期望的:存储所有图像
我尝试使用Subject、ReplaySubject(1)而不是BehaviorSubject,只是为了不初始化值,或者使用带有跳过操作符的BehaviorSubject来获取最后一个值。我不知道我错过了什么。此外,我删除了ngOnDestroy()只是为了知道我是否销毁了整个变量,尽管这没有意义,因为我是在获得值之后才存储它的。
// image-state.service
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ImageStateService {
private imgStateSubject = new BehaviorSubject<string>('');
imageState$ = this.imgStateSubject.asObservable();
constructor() {
}
getImage(val: string) {
this.imgStateSubject.next(val);
}
}//组件A发送的值
onSave(severity: string, data: string) {
this.confirmationService.confirm({
message: 'Are you sure that you want to save it in Gallery?',
accept: () => {
this.imageStateService.getImage(data); // Getting the value
this.messageService.add({ severity: severity, summary: 'Success', detail: 'Data Saved' });
}
});
}//接收值(组件B)
images: Image[];
subscription: Subscription;
constructor(private imageStateService: ImageStateService) { }
ngOnInit() {
this.images = [];
this.subscription = this.imageStateService.imageState$
.subscribe(val => this.images.push
({source: `${val}`, alt: 'Description for Image 1', title: 'Title 1'}));
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}发布于 2018-12-19 07:34:44
BehaviorSubject仅存储当前(最后一个)值。看看ReplaySubject,你可以指定buffer保存在其中。
您可以使用运算符shareReplay将buffer添加到任何流中以存储值。
http://reactivex.io/rxjs/manual/overview.html#replaysubject https://www.learnrxjs.io/operators/multicasting/sharereplay.html
https://stackoverflow.com/questions/53841725
复制相似问题