John Glabb
John Glabb

Reputation: 1621

How to chain eventemitter next method?

I want to execute some other code once event emitted and done. Is there a way to chain the .next() block like this?

@Output() myEvent = new EventEmitter<string>();
this.myEvent.next({‘test string’}).onComplete(console.log('done');

Upvotes: 1

Views: 1488

Answers (2)

Estus Flask
Estus Flask

Reputation: 222696

EventEmitter is an abstraction over RxJS Subject (this is a subject to change), and Subject implements both Observable and Observer. next isn't an operator, it can be seen in Observer interface that next returns no value and cannot be chained.

As for the code above, EventEmitter has emit method for that, while next belongs to Subject API, so emit should be preferred:

@Output() myEvent = new EventEmitter<string>();
this.myEvent.emit({‘test string’});

There is no onComplete method and there is no need for it. Outputs are supposed to stay incomplete until component destruction.

It could be done with

this.myEvent.subscribe(null, null, () => console.log('done'));

But this would result in additional subscription. All destroy logic should go to respective lifecycle hook:

ngOnDestroy() {
  console.log('done');
}

Upvotes: 2

user6749601
user6749601

Reputation:

No, there is no way to monitor this out of the component that emits the event as this is supposed to be kind of "fire and forget".

What you could do is define another @Input-value which gets emitted by the parent component as soon as the "post-event actions" are done. If you monitor this you definitely know when to start follow-up actions.

Upvotes: 0

Related Questions