首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BehaviorSubject问题

BehaviorSubject问题
EN

Stack Overflow用户
提问于 2018-12-19 05:59:39
回答 1查看 98关注 0票数 0

嗯,一切都很好,但并不像我预期的那样。当用户保存图像时,我尝试从组件A获取当前值,并通过服务(使用BehaviorSubject )共享该img并将其存储在组件B中。我知道我总是获得当前值,但我的意图是存储最后一个值并保存我想要的所有图像,而不仅仅是用最后一个值覆盖当前值。

当前问题:我总是只存储最后一张图片。我期望的:存储所有图像

我尝试使用Subject、ReplaySubject(1)而不是BehaviorSubject,只是为了不初始化值,或者使用带有跳过操作符的BehaviorSubject来获取最后一个值。我不知道我错过了什么。此外,我删除了ngOnDestroy()只是为了知道我是否销毁了整个变量,尽管这没有意义,因为我是在获得值之后才存储它的。

// image-state.service

代码语言:javascript
复制
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发送的值

代码语言:javascript
复制
 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)

代码语言:javascript
复制
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();
  }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53841725

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档