SPA Framework/Angular

[Angular] EventEmitter에 관해

범데이 2021. 11. 13. 20:23

1. EventEmitter란?

@angular/core

EventEmitter

 

@Output 디렉티브와 함께 컴포넌트 내에서 사용하여

사용자 정의 이벤트를 동기식 또는 비동기식으로 내보내는 역할을 하고,

해당 인스턴스를 구독하여 해당 이벤트에 대한 핸들러를 등록한다.

class EventEmitter<T> extends Subject<T> {
  constructor(isAsync?: boolean): EventEmitter<T>
  emit(value?: T): void
  subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription
}

 

 

2. 사용 예제

 

먼저, 아래와 같이 "processStart", "processEnd" EventEmitter 인스턴스를 정의한다.

export class MainComponent {
  ...
  @Output() processStart: EventEmitter<any> = new EventEmitter();
  @Output() processEnd: EventEmitter<any> = new EventEmitter();
  ...
}

 

만일 Item 데이터를 가져오는 "getItemsRestAPI()" 라는 REST API 호출을 담당하는 비동기 메서드가 있다고 하자.

 

해당 비동기 메서드의 실행전에 "processStart" 이벤트를 발생시키고,

메서드의 결과가 반환되면, "processEnd" 이벤트를 발생시킨다.

  getItems(): any{
    this.processStart.emit();
    this.getItemsRestApi().subscribe(result => {
        this.processEnd.emit();
      }
    });
  }

 

이후, 각 "processStart", "processEnd" EventEmitter 인스턴스를 구독하여

각 사용자 정의 이벤트가 발생하였을때에 처리할 코드를 넣어줄 수 있다.

this.processStart.subscribe(() => {
  console.log("Get item started!!")
});

this.processEnd.subscribe(() => {
  console.log("Get item finished!!")
});
반응형