0

I'm trying to call a service from a function but i'm getting this error in the console:

Cannot read property 'TestMethod' of undefined

This is my code:

  • app.component.ts:

    constructor(public _service: BackendFileCodeService){
    }
    public editor;
    
     EditorCreated(quill) {
         const toolbar = quill.getModule('toolbar');
         this.editor = quill;
          // console.log(quill)
          toolbar.addHandler('image', this.imageHandler);
    }
    imageHandler(value) {
              //   document.querySelector('input.ql-image[type=file]').addEventListener('click', () => {
              //      console.log('Hello');
              //   });
              const ImageInput = document.createElement('input');
              ImageInput.setAttribute('type', 'file');
              ImageInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
              ImageInput.classList.add('ql-image');
              ImageInput.click();
    
              ImageInput.addEventListener('change', () => {
                  const file = ImageInput.files[0];
                  if (ImageInput.files != null && ImageInput.files[0] != null) {
                    this._service.TestMethod('Hello');
                       }
              });
          }
    
  • BackendFileCodeService:

    import { Injectable } from '@angular/core';
    @Injectable()
    export class BackendFileCodeService {
         constructor() { }
        TestMethod(test){
        return test;
        }
    }
    

I'm trying to call the service inside the function called imageHandler specifically in the

ImageInput.addEventListener

but i'm getting the error mentioned up, i tried to call the service from outside the imageHandler function and every this works as expected.

Note: the service is console log 'hello' as test.

dengApro
  • 3,848
  • 2
  • 27
  • 41
Fares Ayyad
  • 383
  • 1
  • 3
  • 18

1 Answers1

0

Using fat arrow syntax for your imageHandler function should resolve the issue.

imageHandler(value) {...}
...
imageHandler = (value) => { ... }

If you can not use fat arrow syntax, you would need to create a variable to capture the component scope, the most common way is declaring a variable and assigning to this,

self = this;
imageHandler(value) {
 ....
 self._service.TestMethod('Hello');
 ....
}

I see you are aalready using fat arrow syntax below, which is good else you would also need to capture scope for imageHandler.

ImageInput.addEventListener('change', () => {

Read more about function scopes in typescript here,

this and arrow functions

In JavaScript, this is a variable that’s set when a function is called. This makes it a very powerful and flexible feature, but it comes at the cost of always having to know about the context that a function is executing in. This is notoriously confusing, especially when returning a function or passing a function as an argument.

Madhu Ranjan
  • 17,334
  • 7
  • 60
  • 69