Transitioning an Angular logger service to pure Typescript implementation, moving away from Angular-wrapped modules

Delving into the realm of translating Angular to Typescript for the first time has been quite a journey. While I am drawn to the benefits that Typescript offers, I must confess that integrating TS with Angular has proven to be challenging. Take a look at this code snippet:

module logger { 

 exceptionHandlerProvider.$inject = ["$injector"]

  function exceptionHandlerProvider($injector, exception:any, cause:any) { 
  return function(exception: any, cause: any) {
      var $http = $injector.get('$http');
      var alertService = $injector.get('alertService');

      $http({
          url: '/api/log/',
          method: 'POST',
          data: $.param({
              exception: exception,
              cause: cause,
              apiRequest: true
          }),
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      }).error(function(data) {
          alertService.addAlert({ msg: exception, type: 'error' });
          console.log(exception);
      });
  };


}

  angular.module('logger').factory('$exceptionHandler', exceptionHandlerProvider);

}

While the functionality is there, it feels like I'm merely wrapping my Angular code within a module rather than truly harnessing the power of Typescript. My struggle lies in transitioning from the function notation of Angular to the Class syntax of Typescript. Despite numerous attempts, I keep encountering issues such as circular dependencies, incorrect return types, and injector errors.

My latest attempt involves:

module logger { 

export class $exceptionHandlerProvider {

    http: ng.IHttpService;
    alertService: services.AlertService;

    constructor(Http: ng.IHttpService, AlertService: services.AlertService, exception: any, cause: any){
        this.http = Http;
        this.alertService = AlertService;
        return this.$exceptionHandler(exception, cause);
    }

     public $exceptionHandler (exception:any, cause:any) { 
      return function(exception: any, cause: any) {
          this.http({
              url: '/api/log/',
              method: 'POST',
              data: $.param({
                  exception: exception,
                  cause: cause,
                  apiRequest: true
              }),
              headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
          }).error(data => {
              this.alertService.addAlert({ msg: exception, type: 'error' });
              console.log(exception);
          });
      };
    }
   } 
 } 

If anyone could point me towards valuable resources for navigating Angular in Typescript or assist in refining this translation to Typescript, I would greatly appreciate it.

Answer №1

You seem to be facing a circular dependency issue in your code, specifically between $http, $exceptionHandler, and $http again. Additionally, it's worth noting that $exceptionHandler is not a typical object service; rather, it functions as a function. To work around this and declare a class, you can employ the following workaround:

module logger {
    class ExceptionHandler {

        static $inject = ['$injector'];

        constructor(injector: ng.auto.IInjectorService) {
            ExceptionHandler.injector = injector;
            return <any>ExceptionHandler.handle.bind(ExceptionHandler);
        }

        private static injector: ng.auto.IInjectorService;

        private static handle(exception: any, cause: any) {
            var http = this.injector.get<ng.IHttpService>('$http');
            var alertService = this.injector.get<services.AlertService>('alertService');

            http(...);
        }
    }

    angular.module('logger', []).factory('$exceptionHandler', ExceptionHandler);
}

However, I would advise against using this convoluted approach and instead recommend simply adding types to your initial implementation. Remember, TypeScript is not ClassScript.

An alternate approach could be:

module logger {
    class ExceptionHandler {
        constructor(private injector: ng.auto.I.IInjectorService) {
            this.handle = this.handle.bind(this);
        }

        handle(exception: any, cause: any) {
            var http = this.injector.get<ng.I.HttpService>('$http');
            var alertService = this.injector.get<services.AlertService>('alertService');

            http(...);
        }
}

angular.module('logger', []).factory('$exceptionHandler',
    ['$injector', injector => new ExceptionHandler(injector).handle])
}

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

Moving the marker does not update the address

When the dragend event is triggered, the Getaddress function will be called in the following code: Getaddress(LastLat, LastLng , marker,source){ this.http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng='+LastLat+ &apos ...

Utilizing interpolation for a CSS class defined in an external file within Angular 2

Is it feasible to send a variable to a CSS class in an external CSS file within Angular 2, such as: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', sty ...

Issue encountered during retrieval of data from Steam marketplace

My goal is to retrieve the item price information for a single item on the steam market through a GET request. Below is the angularJS script I am currently using: <script> var app = angular.module('csgo', []); app.controller('MainCtr ...

Enhance my Angular routing functionality by introducing optional parameters in my URL

Check out this unique link: http://www.sample.com/novel/info:id/:genre Here, "id" and "genre" are custom variables that I know how to incorporate into the link without any issues. I'm looking to make the "genre" parameter optional. I've come ac ...

What is the best way to showcase content without triggering a file download during a GET Request?

I recently created a webpage that showcases API responses in a neat tabular format. The technologies I used for this project were Angular JS, Servlets, and Java-Rest Assured framework. Each entry in the table includes a link to a log file, which is provid ...

No gripes about incorrect typing when extending interfaces

I tried out the following code snippet here interface OnlyName { name: string } interface MyTest2 extends OnlyName { age: number } let test1: OnlyName; const setTest1 = (v: OnlyName) => { test1 = v console.log(test1) } let test2: My ...

Implementing top level await feature in Angular 16

Issue with ./node_modules/lucid-cardano/esm/src/core/core.js - Error: Module parse failed due to the top-level-await experiment not being enabled (experiments.topLevelAwait must be set to true to enable it). The file was processed using these loaders: ./n ...

What is the reason behind the error Generic indexed type in Typescript?

Here is a scenario where I have a specific generic type: type MapToFunctions<T> = { [K in keyof T]?: (x: T[K]) => void; }; It functions correctly in this instance: type T1 = { a: string }; const fnmap1: MapToFunctions<T1> = { a: (x: st ...

Switching an application from Angular 5 to Angular 8 can lead to unexpected styling problems

My current project is based on Angular version 5.2, but we recently decided to upgrade it to Angular 8 along with updating the Angular CLI. After completing the necessary code refactoring for Angular 8, the application builds successfully without any error ...

When working with NPM workspaces, Typescript encounters compilation errors, but in the remainder of the monorepository, Typescript compiles without any

Our project has been restructured into a mono repository using NPM Workspaces, with the following structure: |-- apps |-- native <-- Does not belong to Workspace |-- web <-- Does not belong to Workspace |-- common ...

I am attempting to implement multiple ng-repeats in order to access and display data from a third level array in my JSON within a table, but I am encountering difficulties in getting it to function correctly

I'm attempting to nest an ng-repeat but it seems like my approach is incorrect. I want to display all the line items in the JSON. Since the JSON value I'm trying to display is a 3rd level array, I attempted nested ng-repeat but it doesn't s ...

Running into strictdi error for a controller that utilizes $inject syntax

After enabling strict-di on my application for minification purposes, I am facing strictdi errors and working on resolving them. One of the controllers is throwing a strictdi error even though I am correctly annotating using $inject following the John Papa ...

Differences Between Angular's $injector and inject FunctionsIn

In my unit tests, I've been experimenting with two methods of injecting dependencies and I started to ponder the differences between them. Despite producing the same end result of the 'calendarSvc' Service object, I'm curious if one met ...

Broaden the scope of a `Record<string, string[]>` by adding a new type of property

When working in Typescript, it appears that defining the type as shown below should create the desired outcome: interface RecordX extends Record<string, string[]> { id: string } However, an error is thrown stating: Property 'id' of t ...

Utilizing Restangular to assign multiple parameters to a variable within the scope variable

Currently learning AngularJS and utilizing Restangular to communicate with a Rails server API. Struggling with grasping the concept of assigning form parameters to a variable in order to use it within my function for posting to the Rails API. Below is an ...

The error message "Unable to access 'useContext' property of null" appeared

I am currently in the process of developing a component library using Material UI, TypeScript, and Rollup. The package has been successfully published, but I am encountering an error when trying to import it into a new project: "Uncaught TypeError: C ...

Using React and TypeScript together with complex types in the UseContext feature may encounter issues

I successfully implemented the ThemeContext as shown in this link, but it only handles one field. I attempted to adapt this concept for a more complex UserContext, where the state is being set but not reflected on the page. You can view the example on Co ...

``What is the mechanism behind callbacks in AngularJS when making a call to a REST service?

Currently, I am diving into the world of AngularJS and REST. The code snippet that I'm analyzing has the term callback repeatedly used in an authentication function. I'm curious to know if "callback" is a JavaScript or Angular keyword, or simply ...

Guide on how to have two controllers execute identical tasks in Angular while modifying the appearance of the website

Trying to recreate Google's homepage functionality using Angular has been challenging for me. Despite watching Egghead videos and studying the API extensively, I couldn't find a specific example for this behavior. Here's what I aim to achiev ...

Duplicating rows in a table using AngularJS for multiple instances

My goal is to construct a table within AngularJS that includes multiple rows per item. I want the output to resemble the following: <table> <tr><td>Item 1 Row a</td></tr> <tr><td>Item 1 Row b</td>< ...