Implementing dependency injection in TypeScript within AngularJS

I am currently in the process of transitioning a component (AngularJS 1.6) from JavaScript to TypeScript.

class NewProjectCtrl {
    price: number;

    static $inject = ['$http'];

    constructor($http) {
        let ctrl = this;
        ctrl.price = '50'; 
        ...
    }

    createProject() {
        $http.post('/api/project', ctrl.project)
        ...
    }
}

angular
    .module('app.projects-selection')
    .component('newProject', {
        templateUrl: 'app/projects-selection/components/new-project/new-project.tmpl.html',
        controller: NewProjectCtrl,
        bindings: {
            user: '<',
        }
    });

While making this migration, I encountered an issue with TypeScript where it raised an error on $http within my createProject method (Cannot find name $http). Most examples I found only showcase dependency injections within the constructor.

Answer №1

Don't forget to include this. Once injected, make sure to utilize this.$http

Here are some styleguide tips for you:

namespace myNameSpace {

  class NewProjectCtrl {
    private static $inject = ['$http'];

    public price: number;

    constructor(private $http) {}

    createProject() {
      this.$http.post('/api/project', ctrl.project)
    }
  }

  class NewProjectComponent implements ng.IComponentOptions {
    constructor() {
      this.bindings: {
        user: '<',
      };
      this.templateUrl: 'app/projects-selection/components/new-project/new-project.tmpl.html';
      this.controller: NewProjectCtrl;
    }
  }

  angular
    .module('app.projects-selection', [])
    .component('newProject', new NewProjectCtrl());
}

Answer №2

When it comes to creating a class, remember that you are not just defining a function. In this case, the $http is injected into the constructor function and remains there - it does not carry over to the createProject function. To ensure access throughout the class, you should store it as an instance property:

private $http;  // It's good practice to declare it first with type hint

constructor($http) {
    this.$http = $http;
}

createProject() {
    this.$http.post('/api/project', ctrl.project)
}

In TypeScript, there is a shorthand notation for this:

constructor(private $http) {
}

createProject() {
    this.$http.post('/api/project', ctrl.project)
}

The use of let ctrl = this appears odd and may not be necessary. Refactoring your code accordingly might look like this:

class NewProjectCtrl {
    price: number = 50;

    static $inject = ['$http'];

    constructor(private $http) { }

    createProject() {
        this.$http.post('/api/project', ctrl.project);
    }
}

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

Generating new elements on the fly using jQuery and passing a string parameter through the onclick event

While dynamically creating HTML, I encountered a syntax error. If I modify href="javascript:startChat(' + user_id + ','video')" to href="javascript:startChat(' + user_id + ','"video"')", I receive an error stating &a ...

Ways to attach jQuery live to the entire window?

tag: I want to trigger specific functions whenever the mouse moves, regardless of its position on the browser window. Currently, I am using the following code snippet: $('html').on('mousemove', function(e) { ... } However, this appr ...

Using Typescript to create a Checkbox Grid that displays pipe-delimited values and implements a custom validation rule

I am currently working with a checkbox grid that contains pairs of AccountIds (consisting of x number of digits) and file names separated by a pipe delimiter. The file names are structured to always begin with either PRC or FE followed by a varying combin ...

Setting up Electron with React and TypeScript: A Comprehensive Guide

I've been developing an app using Electron, React (jsx), and Babel. However, I recently made the switch to TypeScript and I'm struggling to get everything functioning properly. The npm packages I've tried only work for either React or TypeSc ...

Tips for utilizing loops in Node.js to store form data as objects and arrays of objects in MongoDB

Having recently started working with MongoDB, I am incorporating Node.js, Express 4, and mongoose (mongoDB) into my project. I am facing an issue when trying to save form data to mongoDB within a loop, especially because my model contains both objects and ...

What happens with the styling in this project when the CSS file is blank?

As a first-year CS student in university, I have been diving into the world of React.js. Currently, I am exploring a resume project and noticed that both app.js and index.js files are empty. I am curious to know how the styling is achieved in this project. ...

I am facing an issue with my React/Redux API where it is not logging out correctly and displaying [[

As a beginner in the coding world, I've run into some challenges while working with a React/Redux API. Following along with Bucky Roberts' YouTube tutorial, I decided to replace his static names object with an API that I then integrate into my r ...

I encountered an error stating "Module Not Found" while attempting to locate slick-carousel/slick/slick.css. This issue arose while implementing reacy-slick within my Next.js project

While working on my app with Next.js, I wanted to incorporate a carousel like Slick to display images. I followed the official documentation carefully, imported the necessary CSS file, but encountered an error stating "Module Not Found, can't resolve ...

What is the process of implementing a particular FormControl from a FormArray in my HTML file?

My FormArray initialization code is as follows: this.contents.forEach(content=> { this.formArray.push( new FormControl(content.text, Validators.required)); }); Now, I am trying to associate a specific FormControl with my textarea by using i ...

Implementing jQuery during the navigation between Node routes

Below is a snippet of my jQuery code: $(function () { $('.mnav a').click(function () { el = $('.border'); el.addClass('blink'); el.one('webkitAnimationEnd oanimationend msAnimationEnd animatio ...

JavaScript: Obtaining the month based on the week number and year

Can someone assist me in determining the month based on a given week number and year? For example: Week - 48 Year - 2023 Desired Output - 11 ...

Main focus: Implementing dynamic data writing in this particular code scenario

Having trouble dynamically writing data inside my HTML table using JavaScript. As a newcomer to frontend development, specifically JS, I am seeking guidance on making this work smoothly. I've attempted methods like .innerHTML and .innerText without mu ...

Unable to export data from a TypeScript module in Visual Studio 2015 combined with Node.js

Within one file, I have the code snippet export class Foo{}. In another file: import {Foo} from "./module.ts"; var foo: Foo = new Foo(); However, when attempting to run this, I encountered the following error: (function (exports, require, module, __file ...

Tips for streamlining the use of http.get() with or without parameters

retrievePosts(userId?: string): Observable<any> { const params = userId ? new HttpParams().set('userId', userId.toString()) : null; return this.http.get(ApiUrl + ApiPath, { params }); } I am attempting to streamline the two http.get ca ...

The identifier 'before' could not be located

While working with jest and typescript, I encountered an issue when using "before" calls: Cannot find name 'before'.ts(2304) I made sure to have @types/jest installed already. Update: It appears that jest does not have a "before" function - it ...

Unraveling the Cookie with cookie-parser

I've been attempting to decode a cookie without much luck. The cookie looks like this: s%3Ak0tBm_lnBeH4G5pPIbbFKktQl0l4pNU8.d2ZbSvwFjkmVWfcS9Wn0%2Fi2oSnTYI09krfOOWJAXirE. This particular cookie was generated using the express-session module. My unsu ...

Apply a unique design to a class by clicking on a button

There are 3 identical boxes with the same classes and a button: function changeColorAndAddPadding() { /* ??? */ } .box { border: 1px solid; display: inline; } <button onclick="changeColorAndAddPadding();">Click Here</button> <d ...

Updating properties of nested objects in React JS

When I call this function using the onChange property of an input field, the first console.log displays the changed value accurately. However, the second one does not show the expected result. Despite attempting to deep copy newDisplayedAssignment and mak ...

I am not familiar with this HTML element, it's a mystery to me

As I develop a data-recollection view in HTML, I've recognized the necessity of creating something similar to this: To elaborate, it's an image created hastily, with an input where users can enter data. When they click the "+" button, another in ...

Every time I try to loop through my JSON object using an $.each statement, an error is thrown

When I execute an $.each loop on my json object, I encounter an error 'Uncaught TypeError: Cannot read property 'length' of undefined'. It seems that the issue lies within the $.each loop as commenting it out results in the console.log ...