简体   繁体   中英

Passing Angular EventEmitter.emit() as a callback

An event emitter exitEvent is defined within a component app . The question is what if the function is called by passing as a paramater?

For example

app.component.ts

@Output() readonly exitEvent = new EventEmitter<any>();

...

cancel() {
    const self = this;
    const action = {
      callback: this.exitEvent.emit.bind(self),
      callbackParam: true
    }
    action['callback'](true);
  }

In the above example the call will not properly done and populate error like:

ERROR TypeError: "observers is undefined"
    next RxJS
    emit Angular

As you can see the emit method is called on the context of the observable itself, not your component context. So binding it to this aka self is not correct. The correct implementation of your code should look as follows:

@Output() readonly exitEvent = new EventEmitter<any>();

...

cancel() {
    const self = this;
    const action = {
      callback: this.exitEvent.emit.bind(this.exitEvent), // <-- Main change here
      callbackParam: true
    }
    action['callback'](true);
  }

Here you can find some working example . However, I cannot imagine where you could need such implementation.

What's your use case exactly? You can use something like this to preserve original context

  const action = {
    callback: (p) => this.exitEvent.emit(p),
    callbackParam: true
  }
  action['callback'](true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM