你可以在你的服务中使用一个可观察的
app-events
和
app-actions
组件订阅。当你添加一个新的事件时,你可以将新的值推送到Observable中,在Observable中两个组件都将收到更新的值。
https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
事件.service.ts
export class EventService {
private eventsData: Events[] = [];
private eventsSource: BehaviorSubject<any> = new BehaviorSubject<any>(this.eventsData);
public events: Observable = this.eventsSource.asObservable();
constructor() { }
addItemToEvents(event: Event) {
this.eventsData.push(event);
this.eventsSource.next(this.eventsData); // sends updated array to subscribers
}
}
动作.component.ts
export class ActionsComponent implements OnInit, OnDestroy {
private subscription: Subscription;
public events: Event[];
constructor(private _eventService: EventService) { }
ngOnInit() {
this.subscription = this._eventService.events
.subscribe(events => this.events = events);
}
ngOnDestroy() {
if(this.subscription) this.subscription.unsubscribe();
}
}
事件.component.ts
export class EventsComponent implements OnInit, OnDestroy {
private subscription: Subscription;
public events: Event[];
constructor(private _eventService: EventService) { }
ngOnInit() {
this.subscription = this._eventService.events
.subscribe(events => this.events = events);
}
ngOnDestroy() {
if(this.subscription) this.subscription.unsubscribe();
}
}