0

Here is my pdfService, in Angular project looks below. When I call this.formatter() method inside myPDF is not working.

export class pdfService { 

    formatter(value: number): string {
        return new Intl.NumberFormat('en-IN', {style: 'decimal', currency: 'INR'}).format(value);
    }

    myPDF() {
        const doc = new jsPDF();
        doc.text('Values', 10, 25, 'left');
        doc.text(this.formatter(1000), 10, 25, 'left');
        doc.text(this.formatter(10000), 10, 35, 'left');

        window.open(doc.output('bloburl'));
    }

}

if I write method inside myPDF method, it works. below is code.

function formatter(value: number): string {
    return new Intl.NumberFormat('en-IN', {style: 'decimal', currency: 'INR'}).format(value);
}

I need to use formatter method in multiple PDF methods, so where do I write it?

Note: repeating formatter method in all PDF methods is one option but not the correct way.

Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29
Ramesh
  • 1,041
  • 15
  • 39
  • you must miss something. There is no reason `doc.text(this.formatter(1000), 10, 25, 'left');` would not work whereas `doc.text(new Intl.NumberFormat('en-IN', {style: 'decimal', currency: 'INR'}).format(1000), 10, 25, 'left');` does work – Random Aug 06 '19 at 12:17
  • 1
    How do you call myPDF? It needs to be called on the actual instance of `pdfService`, if you just got a pointer to the function and call it with no context, `this` will not be correctly bound. – Dennis Aug 06 '19 at 12:32

1 Answers1

0

This might depend on the way you call your myPDF function, because that can affect how this inside the function will be bound. If you just have a reference to the function and call it without context, this will be undefined. You can circumvent that by binding your function reference to the actual instance - let me show you what I mean by some code:

export class MyClass {
  value = 5;

  func() {
    console.log(this.value);
  }
}


const instance = new MyClass();
instance.func(); // will work of course.

const referenceToFunc = instance.func;
referenceToFunc(); // will not work.

const boundReferenceToFunc = instance.func.bind(instance);
boundReferenceToFunc(); // will work, becuase reference has been bound to the instance.

This answer explains it in greater detail.

Dennis
  • 14,210
  • 2
  • 34
  • 54