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

Dealing with repetitive HTML elements in Angular JS: Tips for managing duplicate code such as headers and footers

After reading the Angular JS introduction, I noticed that there was no mention of a method to write your HTML header and footer code once and have it automatically included on all pages. Is there an official or recommended way to achieve this? ...

Bring in a template in TypeScript with no need for require statement

Currently, I'm utilizing TypeScript along with Angular 1.5 component. In my scenario, I have a custom decorator in place through which I send templates via require function. The setup is functional; however, I am consistently receiving a tslint warnin ...

Can a unique intrinsic type be created from scratch?

Ever since template literals were introduced in Typescript (PR), we've had access to various useful functions in our types: Uppercase Lowercase Capitalize Uncapitalize For more information, refer to the official documentation. Although it may seem ...

When using the ngFor directive in the <template>, the item is shown as [object Object] within the loop of items

When I interpolate a string variable in a repeated <li>, it displays correctly. However, when I place it within a <template><li>, it appears as [object Object]. What could be causing this issue? I have observed various versions of the < ...

Steps to open and configure a Mobile-Angular modal from another controller

Is it possible to use a modal in Angular JS for mobile devices without compromising the layout? I'm having trouble setting up the controller for my modal inside my main controller and passing parameters. Should I consider using ui-bootstrap for this p ...

Bovine without Redis to oversee queue operations

Can Bull (used for job management) be implemented without utilizing Redis? Here is a segment of my code: @Injectable() export class MailService { private queue: Bull.Queue; private readonly queueName = 'mail'; constructor() { ...

Custom pagination page size in AngularJS trNgGrid

I have been working on developing an Angular table using trNgGrid. It's functioning fine, but I am looking to incorporate custom pagination where the user can choose the number of page items to display per page. I checked out the TrNgGrid Global Opti ...

Ensuring Form Accuracy - Mandatory Selection from Group

Currently, in the project I am working on, there are three textboxes that need to be validated to ensure at least one of them has been filled out. I have been researching custom validation with Angular directives and found that it is possible to set the v ...

Utilizing $http (REST) to send information from a form

Struggling to leverage Angular for CRUD processes, especially encountering difficulties with POST requests to the server. This is my controller: angular.module('myModule').controller("ListingCtrl", function($scope, posts) { $scope.addProje ...

The connections of directives

In my Angular application, I am encountering an issue while trying to enhance the functionality of a third-party directive with my own custom directive. The problem lies in the order of instantiation of these directives. The intended usage of the directiv ...

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

Leveraging AngularJS for parent-child communication through bindings in a unique and effective manner

I've come across the following code snippet: <div class="parent"> <div class="child"> and I have two directives, one for parent and one for child. When an event (such as a click) occurs on parent, I want something to happen on child ...

The attribute 'split' is not found on the never data type

I have a function that can update a variable called `result`. If `result` is not a string, the function will stop. However, if it is a string, I then apply the `split()` method to the `result` string. This function always runs successfully without crashin ...

Is there a way to position the Image component from next/image using absolute positioning?

Is it possible to use an element Image from 'next/image' with the CSS style { position: absolute; left: 50% }? It appears that it is not being applied. For example: import React from 'react' import Image from 'next/image' imp ...

Exploring the Functionality of Backend Objects in Frontend TypeScript within the MEAN Stack Environment

Utilizing MongoDB, express.js, angular4, node.js Although a string I retrieve is successful, it's not the same as retrieving the full object... account.service.ts (full, ) import { Injectable } from '@angular/core'; import { Http, Headers ...

Developing a React-based UI library that combines both client-side and server-side components: A step-by-step

I'm working on developing a library that will export both server components and client components. The goal is to have it compatible with the Next.js app router, but I've run into a problem. It seems like when I build the library, the client comp ...

How to Display Prices in Euros Currency with Angular Filter

Can someone help me figure out how to display a price in euros without any fractions and with a dot every 3 digits? For example, I want the price 12350.30 to be shown as 12.350 €. I attempted to use the currency filter but it only worked for USD. Then ...

The type 'MockStoreEnhanced<unknown, {}>' is not compatible with the type 'IntrinsicAttributes & Pick[...]

I'm currently working on creating a unit test for a container in TypeScript. From what I've gathered from various responses, it's recommended to use a mock store and pass it to the container using the store attribute. This method seems to o ...

Numerous asynchronous requests

I'm trying to figure out why the application keeps making multiple ajax calls. Check out this directive: gameApp.directive('mapActivity', function() { return { restrict: 'A', link: function(scope, element, att ...

Ways to include IDs for a checkbox in AngularJS

In the midst of a school project, I am creating an application where users can select items to borrow from the computer services office. The form for entering profile information is complete, but I am encountering challenges with AngularJS checkboxes. The ...