Angular service in typescript with dependency injection and minification

11,390

Just using the $inject syntax. e.g. :

class Service
{
    static $inject = ['$http'];    
    constructor( private $http: ng.IHttpService )
    {
    }

    public MyMethod()
    {
        this.$http.get( "/" )
            .success( null )
            .error( null );
    }
}

PS: I did a detailed video on the subject : http://www.youtube.com/watch?v=WdtVn_8K17E&hd=1

Share:
11,390

Related videos on Youtube

Dreamwalker
Author by

Dreamwalker

....

Updated on September 16, 2022

Comments

  • Dreamwalker
    Dreamwalker over 1 year

    I am trying to get my head round angularjs at the moment. I am currently looking at services I am also using typescript for code.

    Now from samples on the web I have seen that people use something like below for a service in typescript.

    class Service
    {
        constructor( private $http: ng.IHttpService )
        {
        }
    
        public MyMethod()
        {
            this.$http.get( "/" )
                .success( null )
                .error( null );
        }
    }
    

    Now if this is minified I would lose $http from the constructor and angular requires the variable names. So I checked around and found I can use $inject instead of the constructor but this also would get the same minification problem.

    How are people dealing with minification and angular in a typescript context? I am struggling to find some solid docs on how this should be handled. To me this seems odd to have these problems in a modern api so I must be missing something somewhere.

    • ekussberg
      ekussberg
      You can use before uglifyid the "ngAnnotate" module for gulp, so it will prevent loosing of dependencies in angular. For example: gulp.src(paths.ts).pipe(ts(ts.createProject('tsconfig.json')‌​)).pipe(concat('app.‌​min.js')).pipe(ngAnn‌​otate({remove: true,add: true,single_quotes: true })).pipe(uglify()).pipe(gulp.dest('www/js/'))
  • mhelvens
    mhelvens almost 10 years
    But this way, each Service instance gets its own $http reference. In vanilla JavaScript, the angular.factory method is commonly used to access such dependencies in a closure. What best practices would you suggest to achieve this in Typescript?
  • basarat
    basarat almost 10 years
    Services are singletons. There will be only one instance
  • mhelvens
    mhelvens almost 10 years
    Javascript doesn't know about classes (or singletons), and so neither does AngularJS. Services can be anything. I've been offering instantiable 'classes' as services for ages.
  • Trevor
    Trevor about 9 years
    Yes, but AngularJS will do the instantiating and inject the same instance wherever it is requested.