Karu
Karu

Reputation: 1005

Angular communication between two components using subject

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?

Upvotes: 0

Views: 1515

Answers (1)

Barremian
Barremian

Reputation: 31125

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);
  ...

Upvotes: 2

Related Questions