The issue arises when attempting to call a method from the same service within jsPDF in an Angular environment

Below you will find my Angular project's pdfService. I am facing an issue where calling the this.formatter() method inside myPDF is not functioning properly.

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

}

When I include the method within myPDF, it works as expected. See code below:

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

I require the use of the formatter method in multiple PDF methods. Where should I place it?

Note: Repeating the formatter method in all PDF methods is one possible solution but not the ideal approach.

Answer №1

It's crucial to consider how you invoke the myPDF function, as it can impact the binding of this within the function. When calling the function without any context, the value of this may become undefined. To address this issue, you can bind the function reference to the specific instance. Here's a snippet of code to illustrate this concept:

export class MyClass {
  value = 5;

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


const instance = new MyClass();
instance.func(); // This will work as expected.

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

const boundReferenceToFunc = instance.func.bind(instance);
boundReferenceToFunc(); // The correct way to ensure proper binding.

For more detailed information, check out this answer.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining the initial row information from jqGrid

If I use the getRowData method, I can retrieve the current cell content instead of the original data before it was formatted. Is there a way to access the original content before any formatting transformations are applied? Just so you know, I am filling t ...

Is there a different option available in place of the JavaScript confirm function?

I developed an application where I heavily utilized the javascript confirm function. confirm("Do you want to proceed"); However, I am not satisfied with the default appearance of the confirm dialog and would like to implement a customized version with be ...

Scale up each image with the use of Java script

I have a main container with three different sub-containers, each containing an image and text. I want to achieve the effect of zooming in on the image of the specific sub-container when hovering over it. Currently, when I hover over any sub-container, all ...

Verify whether a group of div elements overlaps a fixed div while scrolling

I have a layout with a list of posts and a logo positioned at the bottom of the page. The issue I am facing is that sometimes the title of the posts and the logo overlap, and I want to set the logo's opacity to 0.25 only when the text from .cat-date i ...

Every time I attempt to run "npm install" on Visual Studio Code, I encounter an error

Every time I try to run npm install, I encounter this error. My node version is 18.9.1 and I have exhausted all possible solutions. Any help would be greatly appreciated. '''npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Us ...

It seems that Firefox is ignoring the word-wrap style when the class of a child element is changed

Take a look at this: var iconIndex = 0; var icons = ['check', 'chain-broken', 'flag-o', 'ban', 'bell-o']; $('button:eq(0)').click(function() { iconIndex = (iconIndex + 1) % icons ...

Is it possible to conditionally remove the parent upon the loading of the Router?

Below is the content from my component.html file: <content-placeholder></content-placeholder> <router-outlet></router-outlet> I would like to know if there is a way to hide or remove the <content-placeholder></content-pla ...

Error message: When working with Protobuf, an uncaught reference error occurs because the 'exports

Currently, I am in the process of configuring protobuf to work with typescript. According to the official Google Documentation, all that is needed is to execute npm install google-protobuf and then to include require('google-protobuf'). Unfortu ...

When working with React JS and the react-select library, I am looking to automatically reset the options to their default value once

I am attempting to disable the select list after unchecking the checkbox and resetting the select value back to default, but currently it is retaining the last selected option. I am utilizing React-select for the select and options in this scenario. APP.j ...

Storing information in a Database using AngularJS and PHP

Seeking assistance with connecting Angular to a PHP database. I have successfully retrieved data in my Angular setup, but struggling to save it to the database. Here's the HTML code I'm using: <form ng-controller="AppCtrl" name="add_user"> ...

auto-scrolling webpage as elements come into view

Here is some jQuery code I have: $(".col-md-12").hide(); $(".button-div").hide(); $(".featurette-divider").hide(); $(".footer").hide(); $(".first").fadeIn(1000); $(".second").delay(900).fadeIn(1000); $(".third").delay(1800).fadeIn(1000); $(".fourth").dela ...

Reactjs Invariant Violation caused by the npm package (react-loader)

I'm currently attempting to integrate react-loader into my react component. This is the code snippet I'm using: /** @jsx React.DOM */ var Loader = require('react-loader'); var DisplayController = React.createClass({ // etc ...

Error: Unable to locate module: 'material-ui/styles/colors'

I encountered an issue with the code below, as it failed to compile: import React from 'react'; import { AppBar, Toolbar } from 'material-ui'; import { Typography } from 'material-ui'; import { MuiThemeProvider, createMuiThem ...

"Error message: 'ng' command cannot be found even after completing the installation of Node

Recently, I set up a fresh MacOS Catalina operating system on my computer. When I attempted to run my old project using 'ng serve', I encountered the error message 'ng: command not found'. To troubleshoot, I installed npm 6.12.1 via nod ...

What is the best way to integrate an asynchronously initialized API with a Vuex state?

As I delve into the world of Vue + Vuex, I find myself grappling with the challenge of initializing an API that relies on asynchronous methods. The common solutions I've attempted so far have hit roadblocks - can't use await outside an async fun ...

Using Node.js to implement pagination with the POKEapi through a loop

Recently, I've been experimenting with the POKEapi to display information on 150 different pokemons. This is my first attempt at creating a node.js app as I'm just starting to learn javascript. The challenge I'm facing now is implementing ...

Choose a specific parameter from a line using the body parser in Node.js

Upon receiving a post message, I am having trouble selecting a value from CSV data. Here is a sample of what I receive: { reader_name: '"xx-xx-xx-xx-xx-xx"', mac_address: '"name"', line_ending: '\n', field_delim: & ...

Changing return values with Jest mocks in TypeScript

Here I am again with a very straightforward example. In summary, I require a different response from the mocked class. Below is my basic class that returns an object: class Producer { hello() { return { ...

Prettyprint XML in Angular 8+ without using any external libraries

I am working with Angular 8+ and I need to display XML content in a nicely formatted way on my HTML page. The data is coming from the backend (Java) as a string, and I would like to present it in its XML format without relying on any external libraries or ...

Using Rails 5 and Ajax: Comments will only be appended if a comment already exists

I have been working on a new feature that allows users to add comments to articles using Ajax. However, I have encountered an issue where the comment only gets rendered successfully through Ajax if there is already one existing comment. The database commit ...