Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

function inside async returning as undefined: Angular

I am trying to subscribe to an API call using SSE,

addAsArray(message){
   array.push(message)
}

calling of SSE:

let src = fetchEventSource('api link', {
method: 'POST',
...
async onmessage(e){
   if(e.text.includes('[END]')){
      this.addAsArray(e.text)
   }
}

However, I am getting this error:
TypeError: Cannot read properties of undefined (reading 'addAsArray')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I understood that async functions may require await, hence I tried doing this

async addAsArray(message){
   array.push(message)
}

calling of SSE:

let src = fetchEventSource('api link', {
method: 'POST',
...
async onmessage(e){
   if(e.text.includes('[END]')){
      await this.addAsArray(e.text)
   }
}

However, I am still getting the same error. What did I do wrong here?

>Solution :

In your case, it seems like this inside the onmessage function is undefined. This is because the onmessage function creates its own context, and this inside that function does not refer to the outer scope.

One way to solve this issue is to use an arrow function for onmessage, which does not have its own this and will inherit this from the parent scope. Here’s how you can modify your code:

let src = fetchEventSource('api link', {
  method: 'POST',
  ...
  onmessage: async (e) => {
    if(e.text.includes('[END]')){
      this.addAsArray(e.text)
    }
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading