调用相同服务的方法在 jsPDF 中不起作用,Angular

Calling a method of same service is not working inside jsPDF, Angular

这是我的 pdfService,在 Angular 项目中看起来如下。当我在 myPDF 中调用 this.formatter() 方法时不起作用。

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'));
    }

}

如果我在 myPDF 方法中编写方法,它就可以工作。下面是代码。

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

我需要在多个PDF方法中使用formatter方法,那么写在哪里呢?

注意:在所有 PDF 方法中重复 formatter 方法是一种选择,但不是正确的方法。

这可能取决于您调用 myPDF 函数的方式,因为这会影响函数内部 this 的绑定方式。如果您只是引用函数并在没有上下文的情况下调用它,则 this 将是未定义的。您可以通过将函数引用绑定到实际实例来规避这种情况 - 让我用一些代码向您展示我的意思:

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 更详细地解释了它。