Failure in Dependency Injection in Angular with Typescript

My mobile application utilizes AngularJS for its structure and functionality. Below is the code snippet:

/// <reference path="../Scripts/angular.d.ts" />
/// <reference path="testCtrl.ts" />
/// <reference path="testSvc.ts" />
angular.module('testApp', []);
angular.module('testApp').constant('url','http://whatever');
angular.module('testApp').factory(
'testSvc', ['$http', 'url', testApp.testSvc]);
angular.module('testApp').controller(
'testCtrl', ['testSvc', testApp.testCtrl]);

The app consists of a controller with the following code:

/// <reference path="../Scripts/angular.d.ts" />
/// <reference path="testSvc.ts" />
module testApp{
export class testCtrl {
    public someText:string;
    public httpData:any;
    public urlName:string;
    private data:IData;

    static $inject = ['testSvc'];

    constructor(testSvc) {
        this.someText = 'I am in scope'
        this.data = testSvc.getData();
        this.httpData = {
            putFunc: this.data.putFunc,
            expectPUTFunc: this.data.expectPUTFunc
        }
        this.urlName = this.data.urlName;
    }
}}

In addition, there is a service component within the app coded as below:

/// <reference path="../Scripts/angular.d.ts" />
/// <reference path="testCtrl.ts" />
interface IData{
urlName:string;
putFunc:string;
expectPUTFunc:string;
}
module testApp{
export class testSvc {
    public data:IData;



    static $inject = ['$http', 'url'];

    constructor(private $http, url) {
        this.data = {
            urlName:url,
            putFunc: typeof $http.put,
            expectPUTFunc: typeof $http.expectPUT
        }
    }

    getData(){
        return this.data;
    }
}}

Finally, the necessary script declarations are included in the HTML file:

<script type="text/javascript" src="../Scripts/angular.js"></script>
<script src="testSvc.js"></script>
<script src="testCtrl.js"></script>
<script src="testApp.js"></script>

Despite setting up my Angular dependencies correctly, the controller does not receive the expected dependency on testSvc.getData(). The issue seems to be that testSvc is undefined. Any insights on what might be causing this problem?

Answer №1

Your factory function should return a service factory function, yet you are currently returning the Service class without instantiating it. To correct this issue, modify your code to instantiate an instance that includes the $http and the url parameters, like so:

angular.module('testApp').factory('testSvc', 
  ['$http', 'url', ($http, url) => new testApp.testSvc($http, url)]);

Additionally, ensure to specify the return type of getData() as IData to avoid any potential warnings: getData() : IData

Answer №2

If you prefer, you can keep your testSvc class unchanged and opt for using a service(class) instead of a factory(fn). By utilizing a service, your constructor function will be registered automatically, eliminating the need to use the 'new' keyword and allowing you to provide your injected services in one centralized location.

angular.module('testApp').service('testSvc', testApp.testSvc);

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

Error encountered when making a post request with Angular JS and Node JS: Bad

In my development setup, I am using AngularJS on the front-end with Node.js as the server. This is how I pass data from the user interface: schatApp.controller('registerController', function($scope,$location,$http) { $scope.RegisterCredent ...

Verify if the property in every element of the array is not empty

How can you determine if all employees have a non-null value for the SSN property in the given object? Employees: { id: 0, name: "John", SSN: "1234" } { id: 1, name: "Mark", SSN: "1876" } { id: 2, name: "Sue&q ...

Trying to access a private or protected member 'something' on a type parameter in Typescript is not permitted

class AnotherClass<U extends number> { protected anotherMethod(): void { } protected anotherOtherMethod(): ReturnType<this["anotherMethod"]> { // Private or protected member 'anotherMethod' cannot be accessed on a type para ...

Creating and modifying arrays using AngularJS

There is a feature in my application where clicking the Add button triggers a modal to appear. The modal contains 3 input boxes for filling in details. Once the information is saved, a list is displayed on the main page with the title of the newly added it ...

ngFor filter based on user input

I am working on a 2-step stepper feature where I need to filter the values in my amountArray based on the age of the person. If the person is above 50 years old, display only the values 10000 and 15000. For Euro currency, show values 25000 and 50000. I att ...

Pattern Matching for Excluding Multiple Specific Phrases

I need to restrict what a user can enter into a field based on previous entries that are already in the system. For instance, the user has already entered these values into the database: ["typescript", "C#", "python"] If they type one of these existing ...

How do you define prop types when passing them in Nextjs?

Welcome to my page import { InferGetServerSidePropsType, GetServerSideProps } from 'next' import ProductList from '../../component/product/ProductList' export interface Item { title: string price: number } const products ...

What steps should be followed to create an npm script that can execute multiple commands for running test cases?

When running the end-to-end (e2e) tests for my AngularJS application, I find myself having to execute a series of commands in separate shell sessions: // start the selenium server webdriver-manager start // initialize a http server to host the current fi ...

Is TypeScript's Structural Typing the exception to the rule?

Let me illustrate two scenarios where I encountered difficulties. The first example involves two points: one in 2d and one in 3d: type Point2D = { x: number, y: number }; type Point3D = { x: number, y: number, z: number }; let point2D: Point2D = { x: 10, ...

React App PWA ERROR: Service worker not registered to control the page and start_url

I am encountering an issue while building a progressive web app using Create React App. Lighthouse benchmarking results in an error, indicating that my PWA is not installable. Surprisingly, I face the same problem even when utilizing the official PWA templ ...

The Angular modal service is failing to show up on the screen

I am having trouble implementing the angular modal service in my web application. When I click on the button, the modal does not appear. Can someone help me figure out what I am doing wrong? Builder View <div ng-controller="BuilderController as vm"> ...

A step-by-step guide to integrating a legend on a leaflet map using Angular and the ngx-leaflet plugin

I am attempting to integrate a legend into a map generated using Asymmetrik/ngx-leaflet. The tutorial I followed for creating the map can be found at https://github.com/Asymmetrik/ngx-leaflet. There are two distinct layers on the map, each requiring its ow ...

Make modifications to dxDatagrid using Batch Edit mode for external changes

Currently, I am working with a datagrid that is set up in Batch Edit mode. After sending a request to my server, it sends back new computed values that I want to apply to the datagrid while keeping the Batch Edit mode features intact (such as the green bor ...

Unable to load dynamic data in Angular 2 smart table

Currently, I am utilizing Angular 6 along with smart table by visiting this link: . Everything was functioning smoothly, until the moment I attempted to switch from static to dynamic data: The following code works perfectly and displays all the content ...

Guide on incorporating text input areas into specific positions within a string

Looking for a way to replace specific words in a string with input fields to enter actual values? For example... Dear Mr. [Father_name], your son/daughter [name] did not attend class today. This is what I want it to look like... Dear Mr. Shankar, your ...

AngularJS requires the parameter to be altered with each iteration of the angular-poller

I'm checking out the angular-poller demo located at: I want to customize the factory in order to pass an argument that will help create a dynamic URL, allowing 'greet' to be called with a newTime argument. How can I adjust poller.get() to ...

The web method within the aspx page is failing to execute

On page load, I am attempting to make an ajax request using the AngularJS $http service to fetch JSON data from a web method located in my User.aspx.cs page. The web method is defined as follows: [WebMethod] [ScriptMethod(ResponseFormat=ResponseForma ...

What is the process of incorporating a JavaScript node module into TypeScript?

Having trouble importing the xml2js module as I keep getting a 404 error stating that it's not found. import xml2js from 'xml2js'; Any suggestions on how to properly import JavaScript modules located in the node_modules directory when work ...

axios.get consistently delivers a Promise of type <Pending>

I have been searching for a solution to my issue, but so far none of the suggestions have worked for me. Below is the code that I am struggling with: const Element = () => { async function getEndData() { const data = (await getEnd()) ...

The IDBCursor type does not have a property named 'value'

It appears that the typescript typings are not aware of the value property on the IDBCursor interface. let cursor: IDBCursor; cursor.value ...