我正在尝试让2个组件使用服务相互通信。第一个组件从列表中添加/删除条目,并将接受的条目添加到日历中,第二个组件显示它们。我设法使列表更新,但是在更新第二个视图时遇到了麻烦,主要是在从日历中删除被拒绝的条目时遇到了麻烦。
Calendar.service.ts
private someEvents: AgendaEvent[];
private BehaviorSubject<AgendaEvent[]> = new BehaviorSubject<AgendaEvent[]>([])
private subjectTest: BehaviorSubject<AgendaEvent[]>;
public readAvailableEvents(): Array<AgendaEvent> {
this.availableEvents = new Array<AgendaEvent>();
this.someEvents.forEach((element) => {
if (element.accepted === false) {
this.availableEvents.push(element);
}
});
return this.availableEvents;
}
declineEventById(event: AgendaEvent): Observable<AgendaEvent[]> {
const index = this.someEvents.indexOf(event);
this.someEvents.splice(index, 1);
console.log(this.someEvents);
this.subject.next(this.readAvailableEvents());
this.subjectTest.next(this.someEvents);
return this.subject.asObservable();
}
getAgendaEventsData(): Observable<AgendaEvent[]> {
this.subjectTest.next(this.someEvents);
console.log(this.someEvents);
return this.subjectTest.asObservable();
}
Events.component.ts
events: AgendaEvent[];
constructor(
private calCrud: CalendarCRUDService,
) {
this.calCrud.getAgendaEventsData().subscribe(data => {
console.log(data);
console.log(this.events);
this.events = data;
console.log(this.events); });
}
我想知道我在做什么错。在我的HTML内,我将数据绑定到events数组,而我想要的是从回调返回的数据。唯一缺少的是删除项目时实际上正在更新的视图。 另外,我试图用此代码实现的目的是通知不同的订阅者以讨论不同的主题。因此,为什么在代码中包含subject和subjectTest。
答案 0 :(得分:0)
发出数据后,您将返回可观察对象。请按照此
private subjectTest: BehaviorSubject<AgendaEvent[]> = new BehaviorSubject<AgendaEvent[]>([]);
public subjectTest$ = this.subjectTest.asObservable();
删除“返回this.subject.asObservable();”两种服务方式
Events.component.ts
this.calCrud.subjectTest$.subscribe(data => {
console.log(data);
console.log(this.events);
this.events = data;
console.log(this.events); });
}
答案 1 :(得分:0)
您是否尝试将.bind(this)添加到订阅的末尾?
this.calCrud.subjectTest$.subscribe(data => {
console.log(data);
console.log(this.events);
this.events = data;
console.log(this.events);
}).bind(this);
答案 2 :(得分:0)
您能尝试像下面一样显式调用changeDetection
events: AgendaEvent[];
constructor(
private calCrud: CalendarCRUDService,private cdref: ChangeDetectorRef
) {
this.calCrud.getAgendaEventsData().subscribe(data => {
console.log(data);
console.log(this.events);
this.events = data;
this.cdref.detectChanges();
console.log(this.events); });
}
一些可以尝试的代码建议
在删除时调用该方法。此方法仅发送数据,无需返回可观察的
getAgendaEventsData(): void {
this.getSubjectTest.next(this.someEvents);
}
创建可重复使用的方法以返回您的主题
getSubjectTest():BehaviorSubject<AgendaEvent[]>{
return this.subjectTest;
}
订阅
this.calCrud.getSubjectTest().subscribe(data => {
this.events = data;
});