如何从主题中获取最后一个值? [英] How to get last value from a Subject?

查看:22
本文介绍了如何从主题中获取最后一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 Angular2 组件需​​要通过服务共享数据:

I have two Angular2 components which need to share data via a service:

@Injectable()
export class SearchService {
  private searchResultSource = new Subject<string>()
  searchResult$ = this.searchResultSource.asObservable()

  setSearchResults(_searchResult: string): void {
    this.searchResultSource.next(_searchResult)
  }
}

假设 ComponentA 被渲染并通过 SearchService.setSearchResults 发出一个事件.然后用户导航到 ComponentB,它也订阅了 searchResult$.但是,ComponentB 永远不会观察到 ComponentA 发出的事件,因为它在 ComponentA 时没有订阅 searchResult$> 发出一个事件,因为它不存在.

Suppose ComponentA is rendered and it emits an event via SearchService.setSearchResults. Then the user navigates to ComponentB, which also subscribes to searchResult$. However, ComponentB will never observe the event emitted by ComponentA because it was not subscribed to searchResult$ at the time ComponentA emitted an event, as it did not exist.

如何创建一个 Observable 来向每个新订阅者发出最后一个事件?

How can I create an Observable which emits the last event to every new subscriber?

推荐答案

BehaviorSubject 立即将最后一个值发送给新订阅者:

BehaviorSubject immediately emits the last value to new subscribers:

@Injectable()
export class SearchService {

  private searchResultSource = new BehaviorSubject<string>('');

  setSearchResults(_searchResult: string): void {
      this.searchResultSource.next(_searchResult);
  }
}

ReplaySubject 将所有以前的事件发送给新订阅者.

ReplaySubject emits all previous events to new subscribers.

这篇关于如何从主题中获取最后一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆