0

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?

Karu
  • 935
  • 2
  • 13
  • 32

1 Answers1

2

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);
  ...
ruth
  • 29,535
  • 4
  • 30
  • 57
  • prefer a `ReplaySubject` in cases where there should not be a default value, as `null` could cause unexpected errors – bryan60 Jun 23 '20 at 20:52