pthalacker
pthalacker

Reputation: 2124

Typescript Angular Dependency Injection Failure

I have an app

/// <reference path="../Scripts/angular.d.ts" />
/// <reference path="testCtrl.ts" />
/// <reference path="testSvc.ts" />
angular.module('testApp', []);
angular.module('testApp').constant('url','http://whatever');
angular.module('testApp').factory(
'testSvc', ['$http', 'url', testApp.testSvc]);
angular.module('testApp').controller(
'testCtrl', ['testSvc', testApp.testCtrl]);

and a controller

/// <reference path="../Scripts/angular.d.ts" />
/// <reference path="testSvc.ts" />
module testApp{
export class testCtrl {
    public someText:string;
    public httpData:any;
    public urlName:string;
    private data:IData;

    static $inject = ['testSvc'];

    constructor(testSvc) {
        this.someText = 'I am in scope'
        this.data = testSvc.getData();
        this.httpData = {
            putFunc: this.data.putFunc,
            expectPUTFunc: this.data.expectPUTFunc
        }
        this.urlName = this.data.urlName;
    }
}}

and a service

/// <reference path="../Scripts/angular.d.ts" />
/// <reference path="testCtrl.ts" />
interface IData{
urlName:string;
putFunc:string;
expectPUTFunc:string;
}
module testApp{
export class testSvc {
    public data:IData;



    static $inject = ['$http', 'url'];

    constructor(private $http, url) {
        this.data = {
            urlName:url,
            putFunc: typeof $http.put,
            expectPUTFunc: typeof $http.expectPUT
        }
    }

    getData(){
        return this.data;
    }
}}

and these script declarations in my html

<script type="text/javascript" src="../Scripts/angular.js"></script>
<script src="testSvc.js"></script>
<script src="testCtrl.js"></script>
<script src="testApp.js"></script>

When I run this app the controller never receives its dependency on testSvc.getData() because testSvc is undefined. Where am I going wrong?

Upvotes: 1

Views: 1877

Answers (2)

Blake Bowen
Blake Bowen

Reputation: 1049

You could just leave your testSvc class the same, and use a service(class) instead of a factory(fn). A service registers your constructor function, so you don't have to new it and provide your injected services in three different places.

angular.module('testApp').service('testSvc', testApp.testSvc);

Upvotes: 2

Scott
Scott

Reputation: 21511

A factory must return a service factory function, but you are returning the Service class without instantiating it. You need to change your code to create an instance that passes in the $http and the url, like this:

angular.module('testApp').factory('testSvc', 
  ['$http', 'url', ($http, url) => new testApp.testSvc($http, url)]);

Also just a note, but you haven't specified the return type of getData() as IData so this will create a warning. getData() : IData

Upvotes: 3

Related Questions