Joe
Joe

Reputation: 4234

Using dependency injection with typescript in AngularJs

I'm converting a component (AngularJS 1.6) from javascript to typescript.

class NewProjectCtrl {
    price: number;

    static $inject = ['$http'];

    constructor($http) {
        let ctrl = this;
        ctrl.price = '50'; 
        ...
    }

    createProject() {
        $http.post('/api/project', ctrl.project)
        ...
    }
}

angular
    .module('app.projects-selection')
    .component('newProject', {
        templateUrl: 'app/projects-selection/components/new-project/new-project.tmpl.html',
        controller: NewProjectCtrl,
        bindings: {
            user: '<',
        }
    });

Typescript complains on the $http in my createProject method (Cannot find name $http). All the examples I can find only uses dependency injections in the constructor.

Upvotes: 2

Views: 1294

Answers (2)

John Doe
John Doe

Reputation: 506

You've forgot this. After injecting use this.$http

Also let me suggest you some approach according to styleguides:

namespace myNameSpace {

  class NewProjectCtrl {
    private static $inject = ['$http'];

    public price: number;

    constructor(private $http) {}

    createProject() {
      this.$http.post('/api/project', ctrl.project)
    }
  }

  class NewProjectComponent implements ng.IComponentOptions {
    constructor() {
      this.bindings: {
        user: '<',
      };
      this.templateUrl: 'app/projects-selection/components/new-project/new-project.tmpl.html';
      this.controller: NewProjectCtrl;
    }
  }

  angular
    .module('app.projects-selection', [])
    .component('newProject', new NewProjectCtrl());
}

Upvotes: 1

deceze
deceze

Reputation: 521995

You're creating a class, not a mere function. $http is injected into your constructor function and exists there, but it does not exist in createProject. You need to store it on the instance as property:

private $http;  // should be declared first too, preferably with type hint

constructor($http) {
    this.$http = $http;
}

createProject() {
    this.$http.post('/api/project', ctrl.project)
}

TypeScript has a shorthand for that:

constructor(private $http) {
}

createProject() {
    this.$http.post('/api/project', ctrl.project)
}

let ctrl = this also seems rather weird, I don't think that makes a lot of sense. I don't know what else you're doing in the constructor, but I'd refactor what you have to this:

class NewProjectCtrl {
    price: number = 50;

    static $inject = ['$http'];

    constructor(private $http) { }

    createProject() {
        this.$http.post('/api/project', ctrl.project);
    }
}

Upvotes: 1

Related Questions