Angular communication between two components using subject

筅森魡賤 提交于 2020-08-10 19:17:47

问题


I have two angular components and need to pass in an object from one component to another on a click. My first component has the following

showEventDetails(event: Event) {
    this.eventsService.sendEventDetail(event)
  }

Here Event is my custom model object:

export class Event {
  id: number
  title: string
  description: string
  url: string
  date: string
}

The event service file is as follows:

export class EventsService {
  eventDetailSubject = new Subject<any>();

  constructor() {
  }

  sendEventDetail(event: Event) {
    this.eventDetailSubject.next(event);
  }

  getEventDetail(): Observable<Event> {
    return this.eventDetailSubject.asObservable();
  }

My Second component has the following code to receive the event data.

this.eventsService.eventDetailSubject.subscribe(event => {
      this.eventCal = event
      this.isLoading = false
    }, error2 => {
      this.isLoading = false
      this.hasError = true
    })

However, I notice that I am unable to receive the event data in the second component. What am I missing here? Is there any other way to pass on this event object from one component to another where the second component is not a child of the first one?


回答1:


RxJS Subject will emit only if it receives a value after the subscription. Instead you could use ReplaySubject with buffer size 1. It could buffer the last emitted value and emit it immediately upon subscription.

export class EventsService {
  eventDetailSubject = new ReplaySubject<any>(1);
  ...


来源:https://stackoverflow.com/questions/62543345/angular-communication-between-two-components-using-subject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!