Incorporating external JavaScript files into Angular component files

I have integrated a third-party JavaScript file into my app.component in the following manner:

declare var MarvinJS: any;
import { MarvinJS } from "../assets/js/marvinjslauncher.js";

Now, I am wondering if I can utilize the methods defined in marvinjslauncher.js within my app component class. If so, could you please provide guidance on how to do so? I attempted to use it like this:

export class AppComponent {
  constructor() {
      MarvinJS.MarvinJSUtil.getEditor("#sketch").then(function(sketcherInstance){
            });
}

If there is an issue with how I am importing it, kindly advise me on that as well. Additionally, I have included the marvinjslauncher.js file in index.html. However, I am encountering the following errors:

ERROR TypeError: Cannot read property 'MarvinJSUtil' of undefined
    at new AppComponent (eval at <anonymous> (bundle.js:1312), <anonymous>:16:39)
    at createClass (eval at <anonymous> (bundle.js:321), <anonymous>:11007:26)
    at createDirectiveInstance (eval at <anonymous> (bundle.js:321), <anonymous>:10841:37)
    at createViewNodes (eval at <anonymous> (bundle.js:321), <anonymous>:12204:49)
    at createRootView (eval at <anonymous> (bundle.js:321), <anonymous>:12109:5)
    at callWithDebugContext (eval at <anonymous> (bundle.js:321), <anonymous>:13247:42)
    at Object.debugCreateRootView [as createRootView] (eval at <anonymous> (bundle.js:321), <anonymous>:12707:12)
    at ComponentFactory_.create (eval at <anonymous> (bundle.js:321), <anonymous>:10030:46)
    at ComponentFactoryBoundToModule.create (eval at <anonymous> (bundle.js:321), <anonymous>:3633:29)
    at ApplicationRef_.bootstrap (eval at <anonymous> (bundle.js:321), <anonymous>:5214:57)

Answer №1

After discussing the issue in the comments, here are some recommended fixes for this problem and other code-related issues:

To start, ensure that you add your MarvinJs js file using a <script> tag and confirm that you can access the MarvinJs namespace and utilities in the console.

Next, within your app.component.ts file:

declare var MarvinJS: any; // do not remove
// import statement to be removed
//import { MarvinJS } from "../assets/js/marvinjslauncher.js";

export class AppComponent implements AfterViewInit { // implement AfterViewInit

  constructor() {} // delete any MarvinJs code from the constructor

  ngAfterViewInit(){
       // relocate MarvinJs code from constructor to the ngAfterViewInit method. For more information on AfterViewInit, visit: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
       MarvinJS.MarvinJSUtil
      .getEditor("#sketch")
      .then(function(sketcherInstance){});
  }

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

Strategies for resolving linter problems involving mixins in vue-typescript

Scenario: I am currently working on a project where I am implementing mixins to engage with data from components and other methods. Despite the code functioning as expected, I am encountering errors in Vetur indicating that the method does not exist in ...

Creating a Customized Pop-up Box with Bootstrap CSS and JQuery/Java Integration

I have a filter box that appears when the filter icon is clicked, but it currently lacks Bootstrap styling. I am in the process of upgrading the website to Bootstrap3 HTML5. The current appearance of the filter icon is as follows: However, we want it to ...

Tips for removing a checkbox and customizing a label's style when the label wraps around the checkbox input

Hello, I'm an advanced beginner so I appreciate your patience:) I've had success removing checkboxes and styling their labels when the for="" attribute is present. However, I'm facing a challenge with a form where the labels wrap the input ...

Integrating modules in Angular 2

Exploring the functionalities of Angularjs 2.0, I encountered an issue when attempting to inject a service into a class. Below is the code snippet that's causing trouble: import {Component, View, bootstrap, NgFor, HttpService, Promise} from 'ang ...

Locate the item within the array to retrieve the object's information

I have daily entries in the mongo database and I am attempting to locate a particular entry within an array. For instance, my goal is to find the Coca-Cola entry for this user on the current date using mongoose. "_id": ObjectId("ID"), "user_id": ObjectId( ...

Unable to access the function this.context.getStore in ReactJS Stores due to an error

I currently have the following code: import React from 'react'; import FilterButton from './FilterButton'; import FilterJobsScreen from '../../actions/jobs-screen/FilterJobsScreen'; import JobStore from '../../stores/Jo ...

No form data available during IE10's unload event

My method of saving form data in emergencies by hooking window.unload and sending it via ajax using POST works well in browsers like IE9 and Chrome. However, I have noticed that in IE10, the form data is empty when sent through POST (using GET as a worka ...

Ways to extract innerHTML content from a loaded element generated by using the .load() method

Check out the code snippet below: template.html : <div id="nav"> Welcome to Space </div> layout.html : <div id="content"> </div> $('#content').load("template.html #nav"); ale ...

What is the best way to showcase objects within a specific timeframe determined by their time feature?

As part of my university project, I am working on showcasing the lecture times for students. I am exploring the best method to present this information accurately based on their time properties. The goal is to have each lecture's rectangle space cover ...

Having difficulty entering text into a "Search Input Field" that is a react component in testcafe

Struggling to input text in a "Type to search dropdown" that is a react component. While able to click on the component, typing any text seems to be an issue. Listed below is an example of the code: import { Selector } from 'testcafe'; test(&ap ...

Is the custom attribute event being triggered too soon?

My Unique Component Creation Journey I have meticulously crafted a custom component to enhance the navigation of my application. The core structure consists of an ul element, with each li item dynamically generated based on the contents of the router&apo ...

To encounter an "undefined" response in the following route of an express application, utilize the next('route') function

const express = require('express') const app = express() app.get('/user/:uid', (req, res, next) => { if (req.params.uid === 'lai9fox') next('route') else next() }, (req, res, next) => { res.send(`<h1& ...

ExpressJS receives mysterious object communication from AngularJS controller

Currently, I am working on a project that involves creating a login page for an admin that redirects to a dashboard. The server-side is built using Express.js, while the client-side utilizes AngularJS. The AngularJS controller below is used to retrieve da ...

Assignment of type 'Angular Promise<void>' is not compatible

In the process of developing a website with Angular4 and retrieving data from Contentful CMS API, I am encountering an issue with assigning proper types to the returned data despite seeing the correct types in the console. The example mock data is as foll ...

Troubleshooting issue with changing label text using innerHTML in JavaScript

In need of some advice regarding a javascript function I've been working on: function validateFile() { var file = document.getElementById('fuCSV'); if (file.value == "") { document.getElementById(&apo ...

What is the best way to reset state in a React component when a key is pressed down while typing in an input

I am struggling with handling input submission in a React component when the Enter key is pressed. My component is built using components from material-ui. In the onKeyDown event handler, I try to clear the state by setting the only field in the componen ...

Implementing Dynamic Parent Node Manipulation with Button Clicks in JavaScript

I am currently working on dynamically creating an input field using the append child method along with add and delete buttons to form a tree-like structure. The goal is to be able to create child nodes with add and delete buttons upon clicking the add butt ...

Angular encountered a SyntaxError due to an unexpected curly brace } character

After spending a lengthy hour trying to troubleshoot this issue, I am at a loss as to why it is not functioning correctly. I have been attempting to showcase a row of images on a webpage using Angular based on data fetched from a json file. Unfortunately, ...

Changing the data of a child component that is passed through slots from a parent component in Vue.js

Exploring the world of components is new to me, and I'm currently trying to understand how the parent-child relationship works in components. I have come across component libraries that define parent-child components, such as tables and table rows: &l ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...