页面上有两个放置的组件:
<app-actions></app-actions>
<app-events></app-events>在第一个组件中,我可以添加新事件,如果成功,它将从服务器返回数据。之后,我需要将这些数据添加到组件<app-events></app-events>中。
这两个组件对crud操作使用相同的EventService。因此,当<app-events></app-events>发生更改时,如何通知<app-actions></app-actions>再次从服务器请求数据。
我知道,我可以用输入,输出。
我这么做很好:
class EventService {
private events: any[] = [];
public constructor(
private translate: Http
) {
this.events = this.http.loadEvents();
}
public getEvents() {
return this.events;
}
public addItemToEvents(event) {
this.events.push(event);
}
}然后在模板中:
<div *ngFor="let i in getEvents()"></div>你认为如何?
发布于 2019-03-03 18:54:30
您可以在服务中使用可观察到的app-events和app-actions组件都订阅的服务。添加新事件时,可以将新值推送到可观察到的值,在该值中,两个组件都将接收更新的值。
https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
event.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
}
}actions.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();
}
}events.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();
}
}https://stackoverflow.com/questions/54972276
复制相似问题