Using Angular 6 to invoke a service function within the ngOninit lifecycle hook

I am encountering an issue while trying to implement a service within the ngOnInit method. My goal is to utilize an SVG map where I access elements of the map using the following code:

 let a = document.getElementById("biharsvg")  as HTMLObjectElement;

To display the SVG map in my component.html file, I have added the following code:

<object data="assets/img/bihar.svg" id="biharsvg" type="image/svg+xml"></object>

Within my ngOnInit function, I am referencing the biharsvg ID like this:

let a = document.getElementById("biharsvg")  as HTMLObjectElement;
   a.addEventListener("load", function() {
      var svgDoc = a.contentDocument;
      var wchamparan = svgDoc.getElementById("wchamparan");
      wchamparan.onclick = function() {
      alert("hello");
      this.SvgService.barchart()
    }
 })

All seems to be working fine as I receive an alert message upon clicking. However, when attempting to call a function from my service within that click event, errors arise. The first error appears in Visual Code:

[ts] Property 'SvgService' does not exist on type 'HTMLElement'.
any

Additionally, the console displays the following error:

Uncaught TypeError: Cannot read property 'barchart' of undefined

When I use this code inside onInit, everything works without any issues; trouble only arises when I try to include it within the onclick or addEventListener functions.

Any suggestions on how to address this situation would be appreciated.

Answer №1

The concept of `this` in the `addEventListener()` method pertains to the specific element that triggered the event.

In order to utilize your `class` referenced `this` within `addEventListener()`, it is recommended to create a separate variable (such as `that`) and use it accordingly.

const that = this;
let a = document.getElementById("biharsvg")  as HTMLObjectElement;
   a.addEventListener("load", function() {
      var svgDoc = a.contentDocument;
      var wchamparan = svgDoc.getElementById("wchamparan");
      wchamparan.onclick = function() {
      alert("hello");
      that.SvgService.barchart()
    }
 })

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

Issue encountered in event.d.ts file at line 74, character 76: TypeScript error TS2370: A rest parameter is required to be an array type

I am currently working on a project in Angular 6 and I encountered an issue while trying to integrate Google Maps into my website. When running ng serve, I received the following errors: ERROR in node_modules/@types/googlemaps/reference/event.d.ts(74,76): ...

Issues with implementing Dark mode in TailwindCSS with Nuxt.js

After spending a couple of days on this, I'm still struggling to get the dark mode working with Tailwind CSS in Nuxt.js. It seems like there might be an issue with the CSS setup rather than the TypeScript side, especially since I have a toggle that sw ...

I'm considering incorporating the "react-picky" third-party library for a filterable multiselect component in React Material UI, but it seems to deviate from the principles of Material Design

https://i.sstatic.net/dxpJO.pngInterested in using the third-party library "react-picky" for a filterable multiselect component with React Material UI, but finding that it doesn't align well with Material Design styles. Is there a way to style any th ...

Tips for optimizing data loading in Angular by pre-loading data to prevent unnecessary Firebase reads

Issue: One specific part of my web application is responsible for fetching a large amount of data from Firebase Firestore whenever a user visits that section. This results in hundreds of thousands of unnecessary reads to my Firestore database. Inquiry: Ho ...

Utilizing Angular and TypeScript: The best approach for managing this situation

I need some guidance on handling asynchronous calls in Angular. Currently, I am invoking two methods from a service in a controller to fetch an object called "categoryInfo." How can I ensure that these methods return the categoryInfo correctly and displa ...

The error message "TypeError: router.back is not a function" indicates that

Testing out the back route navigation in next.js and encountering an error during the test: https://i.sstatic.net/O6Nax.png The function for going back: const router = useRouter(); const handleClick = useCallback(() => { if (router ...

Angular encountering a null value within a pre-existing nested object

Upon receiving a fully populated object from my server to my angular service, everything appears correct in Postman and when I use JSON.stringify in the Angular component. However, I encounter an issue when trying to access nested objects within the view. ...

Guide on linking an XML reply to TypeScript interfaces

Currently, I am faced with the task of mapping an XML response (utilizing text XMLHttpRequestResponseType) from a backend server to a TypeScript interface. My approach has been to utilize xml2js to convert the XML into JSON and then map that JSON to the Ty ...

What is the most efficient method to retrieve an API in Angular?

Recently, I dedicated some time to a personal Angular project. While working on it, I decided to experiment with making an API call to PokeAPI in order to retrieve the .svg image of a Pokemon along with its name. After successfully implementing this featur ...

Error: This issue arises from either a glitch in the Node.js system or improper utilization of Node.js internals

I encountered an issue with setting cookies while creating an authentication mechanism for my service. You can read more about it here. Fortunately, I managed to solve the problem. The root of the problem was attempting to send cookies through 2 separate ...

Modifying elements in an array using iteration in typescript

I'm trying to figure out how to iterate over an array in TypeScript and modify the iterator if necessary. The TypeScript logic I have so far looks like this: for (let list_item of list) { if (list_item matches condition) { modify(list_ite ...

[innerText]: Text containing opening angle bracket

Can anyone explain why Angular [innerHtml] is removing text that comes after the left angle bracket? I encountered an issue with a line of HTML content, like so: text1 <text2 <a>link</a> Instead of displaying the content as is, it shows: ...

Issue arises with the Prototype extension failing to function properly once an Angular application has been deployed

Utilizing a C# backend, I decided to incorporate a C# principle into the Angular frontend. Here is what I came up with: declare interface Date { addDays(days: number): Date; addYears(years: number): Date; isToday(): boolean; isSameDate(date ...

Encountering the error "Unable to access the 'user' property of an undefined object when working with Angular and Firebase

Exploring Firebase for the first time while attempting to configure email and Google authentication in an Angular (v5) application. While following a tutorial (), I encounter an error: ERROR TypeError: Cannot read property 'user' of undefined T ...

Cross-origin error triggered by using an external API within a ReactJS application

I'm facing a common CORS issue in my application while trying to call an API. The API I am attempting to access can be found here: https://github.com/nickypangers/passport-visa-api Below is the code snippet used for making the API call: const getVi ...

There was an issue with matching the call for formatting the start date to "dd MMMM yy" in the function

Hey there, while deploying my project, I encountered this error: https://i.sstatic.net/kiXLA.png Error: No overload matches this call. Overload 1 of 4, '(value: string | number | Date): Date', resulted in the following error: Argument with ...

Incorporating a dynamic fill effect into an SVG pie chart

I am looking to animate a pie chart with a variable value that is unknown upon loading. Assuming I fetch the value promptly and convert it into a rounded percentage : var percentage = Math.round(sum * 100 / total); Next, I place this value here : <di ...

Secure a reliable result from a function utilizing switch statements in Typescript

There's a function in my code that takes an argument with three possible values and returns a corresponding value based on this argument. Essentially, it can return one of three different values. To achieve this, I've implemented a switch statem ...

Tips for assigning a type to a variable that is being configured in Typescript

Within my code, I am utilizing the function PanelService.getSetupOrder(route.params.id) which provides me with 4 specific variables: data pending error refresh While researching the documentation, it was mentioned that by specifying data: order, I could ...

What is preventing me from invoking an overloaded function using this approach?

Consider this scenario involving function overloading: function selectItem(x: {type: string; id: number; }[]): number; function selectItem(x: number): {type: string; id: number; }; function selectItem(x): any { /* ... */ } The documentation explain ...