3
votes
  1. Is EventEmitter an RxJS Observable?
  2. In the angular documentation, it explains how to communicate from child to parent component using EventEmitter. Should we use EventEmitter only in component or it can be used angular service also?
  3. In the angular documentation, it explains how parent and children communicate via a shared service that uses observables RxJS Subject. Can we use EventEmitter instead of RxJS Subject in this MissionService example? Please help converting this example with EventEmitter if we can use EventEmitter at all in a service. I'm new to angular.

    https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

I'm confused a bit after reading these related posts:

2

2 Answers

1
votes

EventEmiter extends from RxJs subject and you can use it as Observable.

Angular sources

    export declare class EventEmitter<T> extends Subject<T> {
      __isAsync: boolean;
      constructor(isAsync?: boolean);
      emit(value?: T): void;
      subscribe(generatorOrNext?: any, error?: any, complete?: any): any;
    }

The best practice to sharing data between parent and child components use @Input and @Output

When you need to use service for sharing. You need to use Subject or BehaviorSubject

service example

@Injectable()
export class MyService {
  private data: BehaviorSubject<MyData> = new BehaviorSubject(null);

  getData(): Observable<MyData> {
    return this.data;
  }

  setData(d: MyData): void {
    this.data.next(d);
  }
}

use in component

data: Observable<MyData>;

constructor(private myService: MyService) {}

ngOnInit() {
   this.data = this.myService.getData();
}

use in template

<div>{{data|async}}</div>
0
votes

There are many different ways to handle event scenario's.

The EventEmitter is the most common way to communicate child events to the parent. Say you created a child component and clicked a button there, you might want the clicked event in the parent:

<button (click)="clickEmitter.emit()">button</button>

<child-component (clickEmitter)="buttonClicked()"></child-component>

A shared service (Injectable) can be used to store data for multiple components.

A Subject and BehaviorSubject can be used to share events between components (sometimes via the shared service). For example: i used an authService with a user BehaviorSubject inside to get the logged in user object in every component.

These are just some simple examples amongst many other use-cases.