Sebastian Nemeth
Sebastian Nemeth

Reputation: 6175

Angular2 EventEmitter doesn't raise event when emitted in a callback

I'm developing an Angular2 component which uses the webcam to snap a picture to a canvas element, and extract it as a Blob. Seperately, the Blob and the event work correctly, but when I try to emit the event from within toBlob's callback function, the event is no longer raised for its listeners.

This works:

var self = this;

self.gotSnapshot.emit({}); //Raises the gotSnapshot event correctly.

this.canvas.toBlob(function(blob){
  console.log(blob); //Logs the blob to console correctly.
});

This doesn't:

var self = this;

this.canvas.toBlob(function(blob){
  self.gotSnapshot.emit(blob); //Event is never raised for listeners
});

I'm sure it's because toBlob is executing asynchronously. In Angular1 my instinct would be to do a $timeout and call apply, but I thought for an EventEmitter we don't have to deal with all that anymore?

Anyone know how to get around this?

Upvotes: 2

Views: 937

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658007

This API is not patched by Angulars zone. You need to explicitly make the code run in Angulars zone for change detection to happen afterwards:

constructor(private zone:NgZone){}

someMethod() {
  this.canvas.toBlob((blob) => {
    this.zone.run(() => {
      this.gotSnapshot.emit(blob); 
    });
  });
}

You also don't need self if you use () => instead of function()

Upvotes: 6

Related Questions