What is the best way to include a non-Typed Angular service in a TypeScript class?

I have a module and service in Angular that were originally developed without TypeScript, like this:

MyModule = angular.module('MyModule', ['dependency1', 'dependency2']);
MyModule.factory('MyService', ['$otherDependency', function ($otherDependency) { 
    return { 
        myOperation: function(){...}
    };
}]);

Now, I want to incorporate this service into a TypeScript class without converting everything else. I attempted the following code, but the injected service always ends up being null:

/// <reference path="angular.d.ts"/>
module MyTypescriptModule { 
    export class MyClass extends MyOtherClass {
        static $inject = ['MyService'];
        constructor(private MyService) { ... }
    }
}

Is there a way to achieve this, and if so, what am I overlooking?

UPDATE: I managed to implement PSL's suggestion from their js bin example, with slight modifications to avoid a dependency error, using guidance from this helpful question: Call Angular JS from legacy code

var angularInjector = angular.element($("#divWithNgApp")).injector();
MyService = angularInjector.get('MyService');

Answer №1

class MyTypescriptModule {
    public context: any;
    public customService: any;

    constructor($ctx:any, CustomSvc:any) {
        this.context = $ctx;
        this.customService= CustomSvc;
    }

To access your service in a function, simply refer to it as this.customService.

Answer №2

Angular services are designed to be injected into angular components...

If your component is used by a controller, you can provide an instance:

module SomeModule {
  class MyComponent extends AnotherComponent {
    constructor(myService:MyService) {
    }
  } 
  class MyController {
    constructor(myService:MyService) {
      MyComponent comp = new MyComponent(myService);
    }
  }
}

angular.module('app').controller('MyController', ['MyService', MyController]);

A plunker demo would clarify the explanation further...

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

I am interested in determining the sum of ng-repeat results

I need help with calculating the total amount of ng-repeat items based on a condition. Here is an example of my table structure: <tr ng-repeat="Company in Companies track by $index"> <td>Department</td> <td>Amount</td> & ...

ui-router: Converting URL parameters

Is there a way to seamlessly transform URL parameters? Let me illustrate with a scenario. Our URL structure is like this: /shopping/nuts/:productId /shopping/berries/:productId /shopping/juice/:productId The products in our app, fetched from an API, may ...

The HTMLInputElement type does not contain a property named 'name'

function handleChange(e) { console.log(e.target.name); } <input name="bb" onChange={handleChange} /> Have you ever wondered why the HTMLInputElement element does not have a name attribute in React? ...

By default, the HTML table will highlight the specific column based on the current month using either AngularJS or JavaScript upon loading

I am working with a table of 10 products and their monthly sales data. Using Angular JS, I am looking to highlight the entire column based on the current month and year. Additionally, we will also be incorporating future expected sales data into the table. ...

How can you transform an object literal AST from a TypeScript file into executable code?

Is there a way to convert a JSON or Object Literal file into executable code? const astInJson = {"pos":0,"end":79,"flags":0,"kind":268,"text":"export interface Order {\n\torderId: string;\n\titineraries(id: string): string;\n}&b ...

Utilizing Angular's ng-Grid with Promises

My current setup involves fetching a JSON file through a service to serve as the data source for my grid. The service successfully fetches the data, and the grid renders its basic layout correctly. However, there seems to be an issue with populating the gr ...

Having trouble administering $httpBackend injection

Currently, I am utilizing Angular 1.5 to create mocked services for my current project by referring to this helpful example: https://embed.plnkr.co/qsmx8RUmQlXKkeXny7Rx/ Here is a snippet of the code that I have developed so far: function() { 'use ...

The latest version of Angular, 1.3.0, along with an input of type "

After updating our application to the latest version of Angular, we encountered a breaking change from version 1.3.0 to 1.5.0 that is causing some issues. Specifically, the problem stems from a custom directive we had that allowed us to use the pikaday dat ...

Unable to show the total number of rows in a table depending on the selection from a drop-down menu or input field

Currently, I have a table with a variable number of rows, but it is set to display 10 rows in each page by default since the table is paginated. Now, I am working on adding a text box where users can input the number of rows they would like displayed on e ...

Struggles faced while trying to set up Karma using NPM

Attempting to set up Karma on a system running node v0.10.13 and npm 1.3.2. Tried both with and without sudo permissions. Here is the log: npm http GET https://registry.npmjs.org/karma ... (Error messages related to failed fetches from registry) ... > ...

Disabling Scrolling in AngularJS Material Tab Components

I'm experimenting with AngularJS Material components and struggling with creating tabs. Every time I add a tab, the content inside the child md-content element automatically gets a fixed height with a vertical scrollbar instead of adjusting its heigh ...

Tips for optimizing data loading in Angular by pre-loading data to prevent unnecessary Firebase reads

Issue: One specific part of my web application is responsible for fetching a large amount of data from Firebase Firestore whenever a user visits that section. This results in hundreds of thousands of unnecessary reads to my Firestore database. Inquiry: Ho ...

The readline interface in Node that echoes each character multiple times

After creating a node readline interface for my project, I encountered an unusual issue. this.io = readline.createInterface({ input: process.stdin, output: process.stdout, completer:(line:string) => { //adapted from Node docs ...

ESLint is indicating an error when attempting to import the screen from @testing-library/react

After importing the screen function from @testing-library/react, I encountered an ESLint error: ESLint: screen not found in '@testing-library/react'(import/named) // render is imported properly import { render, screen } from '@testing-lib ...

Exploring Angular Applications with Search Engine Crawlers on ASP.NET

I am currently using AngularJS for my website's front end, and ASP.NET for the back end. I am in need of a headless browser that can easily render content on the server side for web crawlers. I have been looking into Awesomium.NET and WebKit.NET, bu ...

Discover the method of accessing items pushed into an empty array within a view

Is there a way to retrieve the pushed array in the view section? $scope.addCart = function(){ $scope.viewDetails=[]; $scope.viewDetails.push({"name":"mobile"}); $scope.viewDetails.push({"price":"23"}); ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

The property being set in Angular is undefined, causing an error

I am struggling to understand why the code below is not functioning as intended: Main.html <div class="MainCtrl"> <h1>{{message.test}}</h1> </div> Main.js angular.module('myApp') .controller('MainCtrl', f ...

Mastering AngularJS Authentication: A Step-by-Step Guide for the First Submission

I have a login function in Angularjs, but it only works when I submit it for the second time. How can I fix this issue? Here is my code: .controller('LoginCtrl', ['$scope', '$rootScope', '$location', 'Authenti ...

Understanding the significance of emitDecoratorMetadata in transpiled code

I have a question regarding the significance of the emitDecoratorMetadata option when transpiling TypeScript to JavaScript in an Angular 2 environment. If this option is set to false, and metadata is not included in the final code, what impact will it ha ...