使用主题的两个组件之间的角度通信 [英] 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
}
事件服务文件如下:
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?
推荐答案
RxJS Subject
仅在订阅后收到值时才会发出.相反,您可以使用 ReplaySubject
大小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);
...
这篇关于使用主题的两个组件之间的角度通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!