Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle EventEmitter error in event binding

Tags:

angular

Suppose I have this EventEmitter in a child component:

export class ImageUploadComponent {
    ...
    @Output() imageDataEvent: EventEmitter<string> = new EventEmitter<string>();
    ...
}

This child component, depending on what happens may emit something or generate an error:

...
this.imageDataEvent.emit('good');
...
this.imageDataEvent.error('wrong');

The parent component listens to it through event binding:

<app-image-upload (imageDataEvent)="onImageUpload($event)"></app-image-upload>

When 'good' is emitted, onImageUpload is called on parent component and $event contains 'good'.

How to handle the case of 'wrong'? How can I know when the event is an error? How exactly event binding works for good/bad events?

like image 478
edoedoedo Avatar asked Jul 24 '18 15:07

edoedoedo


1 Answers

Angular's EventEmitters are actually an extension of Observables.

It's been said that it's generally best practice to not handle errors in @Outputs. However, taking advantage of Observable error streams can lead to some pretty elegant code, and having access to Observable operators has some very obvious benefits.

The only difference is that Angular's template binding to an Output event handles the Observable subscription to the EventEmitter internally. The solution is to forego the template binding and just subscribe to the component property manually:

<app-image-upload #upload></app-image-upload>

in your parent component:

@ViewChild('upload') upload: AppImageUploadComponent; 

ngAfterViewInit() {

    this.upload.imageDataEvent.subscribe(
        event => console.log('Emission!'),
        err => console.error(`D'oh!`),
        () => console.log('Complete!')
    );

}

This also allows you to use catch or any other Observable operators that you'd need.

like image 59
joh04667 Avatar answered Sep 18 '22 21:09

joh04667