MelbDev
MelbDev

Reputation: 375

JavaScript - Return string value from event listeners

In my Angular App I want to return string value (error message) from an event listener and assign it to a variable.

errorMessage: string = ''; // my variable

im trying to assign the error message to the variable above but its not assigning anything

ngOnInit() {

this.errorMessage = CustomHandler.on("error", function(event: {}) {

console.log(event.message) // The field has an error
return JSON.stringify(event.message)

});

}

What am I missing here?

Upvotes: 0

Views: 798

Answers (2)

Rob Louie
Rob Louie

Reputation: 2671

I mean this just isn't how javascript works. Hard to say 100% since we don't know what CustomHandler.on() returns, but its very unlikely it returns the return value from your function. In theory becuse the event hasn't happened yet, but will in the future.

Don't really know exactly what you want to do, but you probably want something like this:

ngOnInit() {
  CustomHandler.on("error", (event: {}) => {
    console.log(event.message) // The field has an error
    this.errorMessage = JSON.stringify(event.message)
  });
}

In theory now if ngOnInit has been called and also the event you are handling occurs, this.errorMessage will contain the stringified message.

Upvotes: 1

lev
lev

Reputation: 76

I think you are setting event object to be an empty object when you do this

this.errorMessage = CustomHandler.on("error", function(event: {}) {

can you try instead doing this

this.errorMessage = CustomHandler.on("error", function(event) {

Upvotes: 0

Related Questions