如何从另一个组件的数据上重新加载数据?

时间:2019-03-03 18:32:02

标签: angular

页面上有两个放置的组件:

<app-actions></app-actions>
<app-events></app-events>

在第一个组件中,我可以添加新事件,如果成功,它会从服务器返回数据。之后,我需要将此数据添加到组件<app-events></app-events>中。

两个组件都使用相同的EventService进行Crud操作。因此,当<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>

你怎么看?

1 个答案:

答案 0 :(得分:0)

您可以在app-eventsapp-actions组件都订阅的服务中使用Observable。每当您添加新事件时,都可以将新值推送到可观察值,两个组件都将在其中接收更新后的值。

  

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();
  }

}