How can I retrieve a variable from an external JavaScript file in an Angular 2 TypeScript file?

I recently wrote a JavaScript file that is meant to return values to TypeScript files within my Angular project.

var webGlObject = (function() { 
  return { 
    init: function() { 
      alert('webGlObject initialized');
    } 
  } 
})(webGlObject||{})
import { Component, OnInit } from '@angular/core';
import '../../../lib/jquery-3.2.1.min.js';
import '../../../server/getSummary.js';

declare var webGlObject: any;

@Component({
  selector: 'mop-designer-dashboard',
  templateUrl: 'mop-designer-dashboard.component.html',
  styleUrls: ['mop-designer-dashboard.component.css'],
})

export class MopDesignerDashboardComponent implements OnInit {

  debugger;
  scoreBoardList: any = [];
  breadcrumb: any = [];

  constructor() {

    /* prepare breadcrumb */
    this.breadcrumb = [
      {
        label: 'Mop Designer',
        href: '/#/mop-designer'
      }
    ];

    debugger;

    webGlObject.init();



  }

  ngOnInit() {
    console.log('test');
  }
}

However, there seems to be an issue as the declaration of 'webGlObject: any;' does not actually create an object, resulting in the following error:

> ZoneTask.invoke @ zone.js?fad3:339 VM292602:61 Error: Uncaught (in promise): Error: Error in :0:0 caused by: webGlObject is not defined ReferenceError: webGlObject is not defined at new MopDesignerDashboardComponent

Answer №1

The reason for this is the creation of a class and its usage as an object. You can try the following approach: Include the following in your JavaScript file:

var webGlObject = function() {
this.init= function() {
  alert('webGlObject initialized');}}

Then, create an instance in your TypeScript file:

declare var webGlObject: any;
export class YourComponent{
constructor(){
    let wegObj = new webGlObject();
    wegObj.init();
  }
}

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

"Vue3 offers the ability to return a multi-layer object through the Provide-Inject

While implementing provide-inject in my personal project, I encountered an issue where the value returned by inject() was a RefImpl Object. This meant that I had to access the actual value using inject().value.value instead of just inject().value. Here is ...

Changing the text color and background color of a span element when a ng-click event is triggered

There are two buttons, Today and Tomorrow, each with an ng-click function. By default, the button background color is white and text color is red. When the Today button is clicked, the background color changes to blue and the text color changes to white. ...

What is the process of transferring information from one window to another window?

Is there a way to transfer data between two windows? In my parent window, I have a button that redirects to another page with a success button. When the success button is clicked on the child window, I want to display "success" text on the parent window. ...

Pass data from a child controller to its parent using $emit

My goal is to pass values from dropdown lists and input fields in the FirstController to the MainController, and values from datepickers in the SecondController to the MainController. I have been attempting to use $emit and $on but without success. It&apos ...

How can we stop the brief display of a hidden div from occurring?

I have two divs on my webpage - one to display if JavaScript is disabled, and another if JavaScript is enabled. The issue I am facing is that even when JavaScript is not disabled, the div containing the message stating that JavaScript is disabled briefly ...

Declaring a subclass type in Typescript: A step-by-step guide

Would it be feasible to create something like this? export abstract class FilterBoxElement { abstract getEntities: any; } export interface FilterBoxControlSuggestions extends FilterBoxElement { getEntities: // some implementation with different pa ...

Update all unique symbols excluding the initial instance of the addition symbol

I need a solution to replace all non-numeric characters in a string, excluding any leading "+" signs. For example: 1234++!@#$%^&*()_+=-;',.><:" becomes 1234 +1234 becomes +1234 ++++1234 becomes +1234 +1234++!@#$%^&*()_+=-;',.&g ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...

Having trouble interacting with Xpath elements using Selenium and Java?

I have been attempting to access a search bar and submit the query without a SEARCH BUTTON. While I was able to enter the search query using javascriptexecutor, I encountered difficulty when trying to perform an Enter button action as there was no actual E ...

Importing XML data into a JavaScript variable using jQuery without displaying an alert message

Despite previously asking questions about loading XML into a JS variable, I haven't found a satisfactory solution. In my script, I declare a variable before making an ajax request and then assign the result to that variable. However, this only seems t ...

What is the best way to anticipate a return phone call?

Looking to retrieve the largest date from a folder by reading its contents. https://i.stack.imgur.com/KYren.png Here is the code snippet to read the folder, extract filenames, and determine the largest date (excluding today): async function getLastDate ...

"Error: Unable to access the property '$emit' of an undefined value" - VueJS

I'm currently working on implementing a basic authentication system in vuejs. I have a set of objects containing valid usernames and passwords. I am looping through this list to validate the entered username and password. If there is a match, I trigge ...

Tips for displaying content when clicking on the opener containing tables or div elements

This is a snippet of JavaScript code $(document).ready(function () { $(".show-content").hide(); $(".opener").click(function () { $(this).parent().next(".show-content").slideToggle(); return false; ...

The error message "writeUserData is not defined" is indicating that there is an undefined variable in the react code

I'm still learning React and I've been working on a new function: This is my code in summary: class Signup extends Component { constructor(props) { super(props); } componentDidMount() { } writeUserData = (userId, username, email) => ...

"Can you provide instructions on how to focus on a tab that is already open in Firefox

I have a link that, when clicked, opens a new tab in Firefox. <a target="_default" href='/portal.html' > Go to Portal </a> However, each time I click this link again, it refreshes the already opened tab instead of focusing on it ...

Tips on sorting an array within a map function

During the iteration process, I am facing a challenge where I need to modify certain values based on specific conditions. Here is the current loop setup: response.result.forEach(item => { this.tableModel.push( new F ...

The sequencing of AJAX calls on the server side may not necessarily match the order in which they were initiated on the client side

I am working on an ASP.NET MVC application that includes a JavaScript function within a view. Here is the code snippet: function OnAmountChanged(s, fieldName, keyValue, url) { console.log("Get Number: " + s.GetNumber()); console.log(" "); ...

Discover the DOM events present in an HTML response

When sending multiple HTTP requests to a server and receiving a HTML + JS response, I need to determine which responses trigger JS alerts or DOM-based events. Node.js is being used to send the requests. Especially in cases where there is local JS on the c ...

Element.style prevents customization of Rev Slider dimensions

I'm currently attempting to adjust the height of my rev slider from 100% to 80%, but I can't seem to locate the necessary code. Upon inspecting in Chrome, I noticed the following: element.style { max-height: 1080px; margin-to ...

JavaScript recursive function to find the sum of array elements that equals to the given target number n

Currently, I am making my way through the Javascript course available on freecodecamp. However, in one of the lessons that cover recursive functions, I have hit a bit of a roadblock. The code snippet that is causing me confusion is as follows: function su ...