代码之家  ›  专栏  ›  技术社区  ›  POV

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

  •  0
  • POV  · 技术社区  · 6 年前

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

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

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

    两个组件对crud操作使用相同的eventservice。那么,如何告知 <应用程序事件></应用程序事件> 在发生更改时再次从服务器请求数据 <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 回复  |  直到 6 年前
        1
  •  0
  •   Jason White    6 年前

    你可以在你的服务中使用一个可观察的 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();
      }
    
    }
    
    推荐文章