Guide to integrating and utilizing a personalized JavaScript file within TypeScript components in an Angular 2 application

I have created a standard Angular 2 App using angular-cli.

Now, I am trying to incorporate a custom .js file into it. Here is a simplified version of what the file looks like:

'use strict';

var testingThing = testingThing || {};

testingThing.Client = function (name) {
    var self = this;
    console.log(name);

    this.parseUri = function (str) {
        console.log(str);
        return str;
    };

    return this;
};

// Node environment module
if (typeof window === 'undefined') {
    module.exports = testingThing;
}

I am having trouble integrating it into my TypeScript component.

I have attempted the following:

export class TestService {

  something: any;

  constructor() {
    this.something = new testingThing.Client();
    var huh = this.something.new("test name");
    testingThing.parseUri("testParse");
  }

}

I also tried to create typings for it:

declare namespace testingThing{

    class Client {
        new (name : string): /* testingThing.Client */ any;
    }

    function parseUri(str : any): any;
}

However, I keep getting errors in the console stating that testingThing is not defined.

 Cannot read property 'Client' of undefined

When I attempted to import it, I received an error saying that testingThing is not a module.

I have already added myCustom.js to angular-cli.json

"scripts": [
        "./myCustom.js"
      ],

I have tried various solutions from the internet, but none seem to work. I am at a loss as to what I might be doing wrong. Is it my usage, typing definitions, or something else entirely?

I hope the solution is straightforward for those more experienced in frontend programming because I am currently stuck.

Answer №1

In my experience, I found a solution to the same problem that you might be facing. If you're reading this question and looking for help, hopefully, this will work for you too :) While not claiming it's the official way, it certainly did the job for me. It involved some trial and error, with plenty of errors before finally hitting upon the right approach:

  1. To start, include your custom script within <script></script> tags in the index.html file like so:

    <script src="./myCustom.js"></script>
    
  2. You'll need to make some changes in the code as follows:

    • Use 'class' instead of 'interface'
    • Replace 'new method' with 'constructor' (and don't forget to remove the return value declaration)
declare namespace testingThing 
{

      class Client {

        constructor(name: string)
      }

      function testFunction(str: any): string;}

After these adjustments, your code snippet should look something like this:

import { Injectable } from '@angular/core';

@Injectable()
export class TestService {

  somethingElse: any;

  constructor() {
    this.somethingElse = new testingThing.Client("constructor");
    console.log(this.somethingElse);
    this.somethingElse.testFunction("test call to function inside");
  }

}

No need for imports, 'require', or additional variable declarations.

Furthermore, remember to remove your library from the scripts section in angular-cli.json file (or avoid including it altogether) as it is unnecessary.

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

Assign a value to a ReactiveForm within a Jasmine test suite

I am currently working on learning how to unit test a reactiveForm in Angular. My goal is to populate a field with a value and then verify the form's validity after adding that value. Here is where I currently stand: Snippet from my Jasmine test: ...

When hovering over slick text, it becomes hidden because of non-responsive CSS. Are there any solutions to make it responsive?

I can't seem to get the on-hover dates to appear, even though they are rendered when inspecting the page. I suspect it could be related to a responsive CSS issue or class breaking. How can I resolve this? https://i.stack.imgur.com/jyEJb.png https:// ...

What is the process for appending a file extension to a Next.js URL?

For instance, I am attempting to redirect the URL : https://example.com/data/publications to this : https://example.com/data/publications.json I made an attempt using Next.js redirection, but encountered difficulty when trying to add a string that does no ...

Is there a way to prevent continuous repetition of JavaScript animated text?

I'm working on a code that displays letters and words one by one, but I can't figure out how to stop it from repeating. Can someone help me with this? <div id="changeText"></div> <script type="text/javascript"> var te ...

What is preventing type guarding in this particular instance for TypeScript?

Here is an example of some code I'm working on: type DataType = { name: string, age: number, } | { xy: [number, number] } function processInput(input: DataType) { if (input.name && input.age) { // Do something } e ...

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

Encountered a TypeScript error: Attempted to access property 'REPOSITORY' of an undefined variable

As I delve into TypeScript, a realm unfamiliar yet not entirely foreign due to my background in OO Design, confusion descends upon me like a veil. Within the confines of file application.ts, a code structure unfolds: class APPLICATION { constructor( ...

Navigating within a nested view using Angular's UI-Router

I've encountered a puzzling issue that I've been grappling with for the past three days. It seems like a straightforward problem, but for some reason, it's causing me a lot of trouble. The main parent view in my code contains two child view ...

Why does AngularJS $watch only execute once?

Why do the codes in the watch only run once? How can I address this issue? this.$rootScope.$watch('tabType', () => { if (this.$rootScope["tabType"] === TabType.Sent) { this.$scope.refreshSentList(); } else if (this.$rootScope[ ...

Deactivate the button once it's been used | Discord.js version 14

In my index.js, I created a function to respond when a button is pressed and then disable it. client.on("interactionCreate", async (interaction) => { if (interaction.isButton()) { if (interaction.customId === "yes") { co ...

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...

Encountering an error when attempting to parse a JSON Object in Java from an AJAX call

** Latest Code Update ** My JavaScript and Ajax Implementation: $(function() { $("#create_obd").bind("click", function(event) { var soNumber = []; $('#sales_order_lineItems input[type=checkbox]:checked').eac ...

Backend is currently unable to process the request

Whenever a user clicks on a note in my notes page, a request is supposed to be made to the backend to check if the user is the owner of that particular note. However, for some reason, the request is not being processed at all. The frontend is built using ...

Cannot seem to get my AJAX code working correctly to show comments

Having some trouble with my comment system code. The PHP part is working fine, comments are being inserted into the table without any issues. However, I am struggling with the Ajax part. The comments are not being displayed unless the page is reloaded. C ...

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

Is it possible to categorize a JSON object based on its properties and then count the occurrences of each property within

I have an array of objects containing booking information and I need to calculate the count of each booking item in every object. const arr = [ { "ID" : 1, "Name":"ABC", "Bookings":[ { & ...

AngularJS http requests fail to include session cookies when making CORS requests

Here is the script I am using: <script> function eventController($scope, $http) { $http.get("http://example.com/api/Event", {withCredentials: true}) .success(function (response) { $scope.even ...

Can a new EJS file be generated using the existing file as a template?

I am in the process of building a website navbar and I am curious about how to automatically inject code from one ejs file into another ejs file. In Python's Flask framework, this is accomplished using the principle of {% block title%} and in another ...

Struggling to retrieve information from a JSON file and display it within a component?

After accessing the JSON data and storing the necessary values in a dictionary named details, I am encountering an issue where the values are displayed when console logged from inside the function but appear as undefined when console logged in the parent f ...

Unexpected error 500 (Internal Server Error) occurred due to BadMethodCallException

Using Vue 2.0 and Laravel 5.4, I am working on creating a matching system that includes a dynamic Vue component. For example, when someone likes another person, it should immediately show that the like has been sent or if the like is mutual, it should indi ...