Exploring dependency injection in Angular 1 using a blend of JavaScript and TypeScript

I'm currently working on integrating TypeScript into an existing Angular 1.5 application. Despite successfully using Angular services and third-party services, I am facing difficulties in injecting custom services that are written in vanilla JavaScript. Specifically, I need to inject the reportService as shown in the example below.

The issue I encounter is receiving an error stating 'getReportById' is not a function.

class ReportController implements IReportController {

    static $inject = ['$stateParams', 'reportService'];


    constructor(private $stateParams: angular.ui.IStateParamsService, private reportService) {

        this.getReport($stateParams.id);
    }

    getReport(id: number): object {
        reportService.getReportById(id)
            .then(function(res) {
                console.log(res)
            });
    }

}

Below is the service code:

angular.module('reportsServiceModule', [])
    .factory('reportsService', [
        '$http',
        reportsService
    ]);

function reportsService(
        $http
) {

    'use strict';

    var service = {};

    service.getReportById = function(reportID) {
        return 'A promise';
    };

    return service;
}

Answer №1

When developing in AngularJS, the main distinction between working with JavaScript (JS) and TypeScript (TS) is the ability to type units. This difference primarily relates to ensuring type safety within the codebase.

Consider the following:

interface IReportService {
 getReportById: (someType) => string;
}

...
constructor(
  private $stateParams: angular.ui.IStateParamsService,
  private reportService: IReportService
) {
...

In terms of dependency injection, there are typically no issues. If a problem arises with dependency injection in Angular, it will be flagged by an error message from the injector.

The real issue at hand here is the absence of strict mode utilization. By incorporating the use strict directive or leveraging the alwaysStrict option in TS, any erroneous usage would be identified explicitly - such as the unavailability of the reportService variable within the getReport method.

A corrected version would resemble:

getReport(id: number): object {
    this.reportService.getReportById(id)
    ...

Answer №2

It appears to be a typographical error.

You've specified a reportsService

.factory('reportsService')

However, you have injected a different service

static $inject = ['$stateParams', 'reportService'];

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

Firebase Database: Unidentified node kind with separate Firebase initialization process

In order to replicate this issue, a minimal repository can be found at: https://github.com/ljrahn/firebase-unknown-node-type The problem arises when the firebase initialization logic is separated into a distinct package and then imported. This leads to an ...

Pause for a minimum of 2 seconds after ajax has been completed before proceeding with transition.next() using Vue.js

For the smooth transition after completing an ajax call, I need to display the spinner for a minimum of 2 seconds. Below is my code, which unfortunately isn't functioning as expected: route: { data(transition) { this.getDelayedData(); ...

React - Obtain User Login Details and Verify

I am working on a React project that includes a Login Form. The code has been organized into small components for reusability, but I am unsure of how to retrieve and validate user credentials (username and password). Is there a method available to validate ...

How can we incorporate methods using TypeScript?

I'm currently diving into TypeScript and encountering some challenges when trying to incorporate new methods into the DOM or other pre-existing objects. For instance, I'm attempting to implement a method that can be utilized to display colored te ...

Day Change Triggers React [Native] View Update

I've been working on a React Native component that needs to update itself when the day changes, regardless of user interaction. Is there another method besides using setInterval for this task? If I use setTimeout in my viewDidLoad function with the n ...

The NodeJS server encountered an issue when attempting to load the JavaScript modules

Hey everyone. I'm currently using Node.js and Express.js for the back end of my web application, but I keep running into issues with the server trying to bind references in the source code. Here's the structure of my app: src/ - static/ - ...

Node server quickly sends a response to an asynchronous client request

Apologies for my lack of writing skills when I first wake up, let me make some revisions. I am utilizing expressjs with passportjs (local strategy) to handle my server and connect-busboy for file uploads. I believe passport will not have a role in this pr ...

Altering the playback of a flash object using HTML or JavaScript

Can the playback speed of a flash object be adjusted without recompiling the object, like through HTML attributes or JavaScript? Appreciate any help in advance ...

Generating Speech from Text using jQuery API in HTML

Can a website be created to detect textbox text upon longClick by the user, and function across various browsers? The site should also have mobile compatibility. Appreciate any help! ...

Troubleshooting encoding problems with Google Cloud's Speech-to-Text API using Node.js

I'm currently working on a project that involves capturing audio from a user's microphone and sending it to a server for translation using Google's Speech-to-Text API. I am utilizing navigator.mediaDevices.getUserMedia() to access the audio, ...

Decoding a JavaScript object when receiving it as JSON through a POST request

While browsing through various SO posts, I came across the statement "javascript is JSON". However, I am struggling to apply this concept in my application. My issue arises when I try to perform a POST request using jQuery. $.ajax({ type: &apo ...

Assign a specific value to each object

Receiving data from the backend in a straightforward manner: this.archiveService.getRooms(team).subscribe( res => { this.form = res; this.form.forEach(el => { el.reservation.slice(-6).match(/.{1,2}/g).join('/'); }); }, ...

What is the best way to trigger an API call every 10 seconds in Angular 11 based on the status response?

I am in need of a solution to continuously call the API every 10 seconds until a success status is achieved. Once the success status is reached, the API calls should pause for 10 seconds before resuming. Below is the code I am currently using to make the A ...

Typescript constructor that accepts an object as an argument instead of traditional parameters

My constructor is becoming lengthy and not structured the way I would prefer. I am looking to pass an object to my constructor so that I can access fields by their names. Here is how the class looks currently. export class Group { id: string; constru ...

Can anyone help me get my carousel to work properly?

I am facing a carousel problem in my personal exercise project. I have gathered HTML, CSS, and JavaScript from the internet and am attempting to integrate them all together. //Sidebar script start $(document).ready(function () { var trigger = $(&apo ...

Unable to assign focus to textbox

In my chrome extension, I have implemented two text boxes - one for entering a URL and the other for LDAP. Upon clicking on the extension icon, a popup page opens where I automatically fill the URL text box with the current page's URL using the code s ...

What is the most effective way to determine the data type of a variable?

My search skills may have failed me in finding the answer to this question, so any guidance towards relevant documentation would be appreciated! I am currently working on enabling strict type checking in an existing TypeScript project. One issue I'v ...

What is the functionality of the "async:false" setting in a jQuery AJAX request?

I understand the purpose and usage of {async:false} in jQuery AJAX requests. However, I am curious to know how this operates synchronously. What is the mechanism behind it? ...

Ensuring the validity of an HTML form by including onClick functionalities for additional form elements

I am working on a form that I put together using various pieces of code that I found online. My knowledge of HTML and JavaScript is very basic. The form includes a button that, when clicked, will add another set of the same form fields. Initially, I added ...

Can the color of text be adjusted (to either white or black) based on the background color (in any color and format)?

To achieve a text color that contrasts well with any background, I need to make sure it's either black or white. The background in my app can vary in color and format, so finding the perfect solution has been challenging. Using mix-blend-mode doesn&a ...